node.js - 有没有正确的方法来解析大量的 JSON?(长,bigint,int64) [英] node.js - Is there any proper way to parse JSON with large numbers? (long, bigint, int64)
问题描述
当我解析这一小块 JSON 时:
When I parse this little piece of JSON:
{ "value" : 9223372036854775807 }
这是我得到的:
{ hello: 9223372036854776000 }
有什么办法可以正确解析吗?
Is there any way to parse it properly?
推荐答案
不适用于内置 JSON.parse.您需要手动解析它并将值视为字符串(如果您想对它们进行算术运算,则有 bignumber.js) 您可以使用 Douglas Crockford JSON.js 库作为您的基础解析器.
Not with built-in JSON.parse. You'll need to parse it manually and treat values as string (if you want to do arithmetics with them there is bignumber.js) You can use Douglas Crockford JSON.js library as a base for your parser.
EDIT2(原始答案后 7 年)-使用标准 JSON api 可能很快就能解决这个问题.看看这个 TC39 提案,将源字符串的访问权限添加到 reviver 函数 - https://github.com/tc39/proposal-json-parse-with-source
EDIT2 ( 7 years after original answer ) - it might soon be possible to solve this using standard JSON api. Have a look at this TC39 proposal to add access to source string to a reviver function - https://github.com/tc39/proposal-json-parse-with-source
我为你创建了一个 package :)
I created a package for you :)
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('
big 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));
输出:
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}
这篇关于node.js - 有没有正确的方法来解析大量的 JSON?(长,bigint,int64)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!