datalanche / json-bignum

Node.js JSON replacement which handles 64-bit integers and arbitrary-precision decimals.
MIT License
24 stars 5 forks source link

Strings with leading 0s are accepted but produce invalid JSON #6

Open eug48 opened 5 years ago

eug48 commented 5 years ago

i.e.

const bignumJSON = require('json-bignum')

> bignumJSON.stringify({key: new bignumJSON.BigNumber("0123")})
'{"key":0123}'

> JSON.parse(bignumJSON.stringify({key: new bignumJSON.BigNumber("0123")}))
SyntaxError: Unexpected number in JSON at position 8

I know the bug is mainly in the code using json-bignum but by allow invalid JSON to be produced the bug is allowed to propagate into other systems.. Perhaps strings with leading 0s should be rejected with an exception in the BigNumber constructor? https://github.com/datalanche/json-bignum/blob/68f270db0ec25f6b19260103e5127a2f9424405e/lib/bignumber.js#L11

BTW, thanks very much for this simple & effective package.

rpedela commented 5 years ago

What does JSON.parse() and JSON.stringify() do in this case?

eug48 commented 5 years ago

In Javascript syntax 0123 is treated as an octal constant, but 09123 throws an Error in Firefox but is converted to 9123 in Chrome & Node

rpedela commented 5 years ago

I think throwing an error is fine then. I would be happy to accept a PR. Thanks!