Home > Software design >  How to make json.parse treat all the Numbers as bigint?
How to make json.parse treat all the Numbers as bigint?

Time:10-21

I have some numbers in json which overflow the Number type, so I want it to be bigint, but how?

{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}

CodePudding user response:

If you got some condition to identify which exactly numbers should be treated as BigInt (e.g. it is number greater than 1e10) you can make use of second parameter of JSON.parse (reviver):

const input = `{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}`,


      output = JSON.parse(
        input, 
        (_, value) => 
          typeof value === 'number' && value > 1e10
            ? BigInt(value)
            : value
      )
      
console.log(typeof output.bar[0][0])
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use a callbck in JSON.parse to do something with the numbers.

A BigInt value, also sometimes just called a BigInt, is a bigint primitive, created by appending n to the end of an integer literal, or by calling the BigInt() constructor (but without the new operator) and giving it an integer value or string value.

const json = '{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}'


const data = JSON.parse(json, (_, v) =>
  typeof v == "number" ? BigInt(v) : v
);

console.log(typeof data.foo[0][0])
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related