How to get correct integer while using JSON.parse()?

"3820228000000079015 " this is the actual integer I got from the response while using API from javascript. For getting this id from the whole response, I am using JSON.parse() . Then I got the id as 3820228000000079000. see the different. last three digits were made as 000 . This is showstopper for me. Please help me. how to get the correct integer?

That integer is way beyond what JS considers to be a safe integer.

If you’re not going to perform math on that id, consider adding double-quotes before and after that value in the JSON string before passing it to JSON.parse so the id is instead a string.

If you made the API, consider returning the id as a string.

There’s also libraries for handling JSON with big integers.

Thanks for your reply @kevcomedia. There is no need for math operation on it. But to add double-quotes, that id should be taken from the whole response, right?. The exact position of it should be known. so how to do that? please explain

You could use a regex to find it. Assuming the key is called "id", you could use:

const jsonIdRegex = /("id"\s*:\s*)(\d+)/;

Then use .replace on the JSON string.

Note that the "id" key and the value are wrapped in their own pairs of parentheses. This is so we could refer to them when doing the replace (the $1 and $2 in the replacement string refer to the parts of the original string that match the patterns in the first and second pairs of parens in the regex, respectively):

json.replace(jsonIdRegex, "$1\"$2\"");

Notice the (escaped) double quotes around $2. It’s what will add the quotes before and after the id value.

Thanks a lot @kevcomedia. It is working.:blush: