Parsing big numbers in JSON to strings

javascript, json, regex, windows

Solution

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

Problem

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 JSON text and turn all the big ints into strings. I'm using JavaScript in a Windows 8 app and its got to be dealt with client side. Got me stumped so far. The main issue is I have to do this after I receive the response from an XMLHTTPRequest and cant change the original format of the JSON e.g ``` { "data" : { "username":"Brad", "userID":941022167561310208, "location":"London" } } ```

Original source

Related problems