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.

Diptangsu Goswami
  • 4,823
  • 3
  • 23
  • 34
  • 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. – user2864740 Aug 08 '20 at 07:32
  • https://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.) – user2864740 Aug 08 '20 at 07:38

2 Answers2

2

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

sromeu
  • 276
  • 2
  • 7
  • thank you for reply. Please let me how to solve it? – Masum Billah Aug 08 '20 at 07: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 08 '20 at 07:53
  • @sromeu your good suggest. I think it's just a string, then solved it. – Masum Billah Aug 08 '20 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);
Maxime Helen
  • 1,305
  • 6
  • 15