Why json number changed, when do json.parse a string?

Viewed 165
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 Answers

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

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);

Related