3
let string = `{"access_token": "someThingsHere", "user_id": 17841436766171705}`;

let resultObject = JSON.parse(string);

console.log(resultObject);

Output:

{access_token: "someThingsHere", user_id: 17841436766171704};

Here 'user_id' was changed. But why? Please help me and describe it.

2
  • 2
    IEEE-754 double-64 only has ~17 relative digits of precision. For INTEGERS, this is a distinct range with a positive limit of ~2^53, which is less than a native int64 (2^64) type. Ideally the source would use an OPAQUE STRING instead of a number. Up to int32 is OK. Aug 8, 2020 at 7:32
  • stackoverflow.com/a/13502497/2864740 — a limit is not “strongly” specified in JSON, although keeping integers to int32 will avoid JSON <-> JS transform issues such as that encountered. Some providers like Json.NET will work just fine with int64. (Very few languages support an int53 as a discrete limit, so such is less of an interesting breakpoint.) Aug 8, 2020 at 7:38

2 Answers 2

2

It is probably because the value is too high for JSON.parse(), take a look at this thread.

3
  • thank you for reply. Please let me how to solve it? Aug 8, 2020 at 7:38
  • @MasumBillah as some people have suggested already, you could treat the user_id as a string instead, so you are able to parse it correctly. I assume that you are not going to make arithmetic operations with it, so it would not modify your app at all.
    – sromeu
    Aug 8, 2020 at 7:53
  • @sromeu your good suggest. I think it's just a string, then solved it. Aug 8, 2020 at 12:52
-2

The issue is your id is higher than Infinity or Number.MAX_SAFE_INTEGER, and Javascript overflows the number.

The good news is the input has a string type, so we can manipulate it as-is with a Regex. We just have to append quotes around the number so JSON.parse will interpret this as string

let string = `{"access_token": "someThingsHere", "user_id": 17841436766171705}`;
string = string.replace(/("user_id":\s?)([\d]*)/, '$1"$2"');

let resultObject = JSON.parse(string);
console.log(resultObject);

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.