String to JSON parse issue with number conversion

Viewed 760

Hi Here I am using JavaScript to convert string to Json object,Here below my code

    const json = '{"result":true, "count":42,"groupID": 80000000000000809}';
    const obj = JSON.parse(json);
    console.log(obj);

result is

Object { result: true, count: 42, groupID: 80000000000000820 }

but required output is

{ result: true, count: 42, groupID: 80000000000000809 }

Why the groupID value is changing during the conversion.Please help me to resolve this.

Thanks for your response. I have found solution for this.

const json = '{"result":true, "count":42,"groupID": 80000000000000000809}';
const obj = JSON.parse(json.replace(/("[^"]*"\s*:\s*)(\d{17,})/g, '$1"$2"'));

console.log(obj);

The above code I have used string replace method to replace big-integer into string.

2 Answers

The integer you are trying to parse is too large. JavaScript only supports up to 53-bit integers, so the maximum value for a Number type in JavaScript is +/- 9,007,199,254,740,991. Any larger and you'll need to use a BigInt. See here for how to work with large integers in JavaScript.

I would recommend changing groupID in your API response to a string rather than an integer.

If you can't do this, then you could also try using a JSON parsing library that can handle BigInt types, e.g. json-bigint.

You can always check Number.MAX_SAFE_INTEGER(). Let's compare this result with the number you're working with:

9007199254740991

80000000000000826

Your number appears to be over the technical maximum that JavaScript supports with integers. I tested with a few other numbers, they appear to have similar problems. Documentation...

The Number.MAX_SAFE_INTEGER constant represents the maximum safe integer in JavaScript (253 - 1).

For larger integers, consider using BigInt. (Source: MDN Web Docs: Number.MAX_SAFE_INTEGER

You can always use a string, though, since it is likely that you'll actually be getting this JSON from a web-server, rather than locally defined:

const json = '{"result":true, "count":42,"groupID": "80000000000000809"}';
const obj = JSON.parse(json);
console.log(obj);

Related