JSON.parse with bigints support
npm install @pgherveou/json-bigintJSON.parse/stringify with bigints support. Based on Douglas Crockford JSON.js package and bignumber.js library.
While most JSON parsers assume numeric values have same precision restrictions as IEEE 754 double, JSON specification _does not_ say anything about number precision. Any floating point number in decimal (optionally scientific) notation is valid JSON value. It's a good idea to serialize values which might fall out of IEEE 754 integer precision as strings in your JSON api, but { "value" : 9223372036854775807}, for example, is still a valid RFC4627 JSON string, and in most JS runtimes the result of JSON.parse is this object: { value: 9223372036854776000 }
==========
example:
``js
var JSONbig = require("json-bigint");
var json = '{ "value" : 9223372036854775807, "v2": 123 }';
console.log("Input:", json);
console.log("");
console.log("node.js bult-in JSON:");
var r = JSON.parse(json);
console.log("JSON.parse(input).value : ", r.value.toString());
console.log("JSON.stringify(JSON.parse(input)):", JSON.stringify(r));
console.log("\n\nbig number JSON:");
var r1 = JSONbig.parse(json);
console.log("JSON.parse(input).value : ", r1.value.toString());
console.log("JSON.stringify(JSON.parse(input)):", JSONbig.stringify(r1));
`
Output:
`
Input: { "value" : 9223372036854775807, "v2": 123 }
node.js bult-in JSON:
JSON.parse(input).value : 9223372036854776000
JSON.stringify(JSON.parse(input)): {"value":9223372036854776000,"v2":123}
big number JSON:
JSON.parse(input).value : 9223372036854775807
JSON.stringify(JSON.parse(input)): {"value":9223372036854775807,"v2":123}
``
- RFC4627: The application/json Media Type for JavaScript Object Notation (JSON)
- [Re: \[Json\] Limitations on number size?](http://www.ietf.org/mail-archive/web/json/current/msg00297.html)
- Is there any proper way to parse JSON with large numbers? (long, bigint, int64)
- What is JavaScript's Max Int? What's the highest Integer value a Number can go to without losing precision?
- Large numbers erroneously rounded in Javascript