Skip to content Skip to sidebar Skip to footer

Parsing Big Numbers In Json To Strings

I'm trying to tackle the issue with JSON.parse() rounding big numbers. I know why this is happening but am looking for away around it. I was thinking a regex which could parse the

Solution 1:

Disclaimer:

This is an old answer, and the question is even older. You shouldn't ever be parsing JSON with regular expressions - it's too brittle of a solution, and is liable to break at random. The right way to do this is to parse the entire JSON string, then use code to convert string values to numbers, e.g. parseInt(jsonData.data.userID).

An even better way to do it is to fix it on your back-end so your client doesn't have to do this.


Here's the regex to wrap all integers with quotes. If you wanted to do this only for long strings, change + to {9,} (or any int).

var json = ('{"data":{"username":"Brad","userID":941022167561310208,"location":"London","test":"3908349804","test2":"This already exists in 034093049034 quotes"},"list":[3409823408,3409823408,"A list 234908234"]}');
json = json.replace(/([\[:])?(\d+)([,\}\]])/g, "$1\"$2\"$3");
json =JSON.parse(json);

See example: http://jsfiddle.net/remus/6YMYT/

Edit Updated to accommodate lists as well.

Here's the regex in action: http://regex101.com/r/qJ3mD2

Solution 2:

I know this is a very old question, but this is the solution you can use if you are using npm. Javascript can handle bigInt of value 9007199254740991docs. You can use this npm package to parse JSON's containing large numbers.

Install your package

npm i json-bigint

Then use it like this.

varJSONbig = require('json-bigint');
let result = JSONbig.parse(<your-json>);

Solution 3:

If you need to use it as a string then just save it as a string, with "":

{"data":{"username":"Brad","userID":"941022167561310208","location":"London"}}

You also have a misstake username => "username".

You can also parse it to integer with parseInt() later

For updated question: Then you need to surround your number with "" with regexp:

s='{"data":{"username":"Brad","userID":9410221675613105435234324235235235235235523208,"location":"London"}}';
s = s.replace(new RegExp('"userID":([0-9]+),',"g"),'"userID":"$1",')

example: http://jsfiddle.net/E4txx/

Post a Comment for "Parsing Big Numbers In Json To Strings"