2

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]]}
Yevgen Gorbunkov
  • 14,071
  • 3
  • 15
  • 36
mihebo
  • 35
  • 4
  • 1
    Probably there's answer available here: [node.js - Is there any proper way to parse JSON with large numbers? (long, bigint, int64)](https://stackoverflow.com/questions/18755125/node-js-is-there-any-proper-way-to-parse-json-with-large-numbers-long-bigin) – koloml Oct 20 '21 at 10:34
  • SAD. I'd like to get some build-in solution... – mihebo Oct 20 '21 at 10:37
  • I suggest to use strings and then convert them into `BigInt` numbers. Like some REST APIs doing (like Discord API with BigInt IDs). It's much easier and you event can convert such variables to `BigInt` using built-in converter. – koloml Oct 20 '21 at 10:39

2 Answers2

2

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])
Yevgen Gorbunkov
  • 14,071
  • 3
  • 15
  • 36
  • 1
    A test could be based too on ... [`Number.isSafeInteger`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger) – Peter Seliger Oct 20 '21 at 11:01
2

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])
The Fool
  • 10,692
  • 4
  • 27
  • 50