node.js is there any proper way to parse JSON with large numbers? (long, bigint, int64)

前端 未结 2 1112
傲寒
傲寒 2020-11-27 07:11

When I parse this little piece of JSON

{ \"value\" : 9223372036854775807 }

that\'s what I get

{ hello: 9223372036854776000          


        
相关标签:
2条回答
  • 2020-11-27 07:53

    you can use this code for change big number to string and use correctly

    let obj = '{ "value" : 9223372036854775807, "value1" : 100 }'
    let newObj = JSON.parse(obj.replace(/([0-9]{15,30}$\.{0,1}[0-9]{0,})/g, '"$1"'));
    console.log(newObj);

    0 讨论(0)
  • 2020-11-27 08:00

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

    EDIT1: 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('\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}
    
    0 讨论(0)
提交回复
热议问题