Since JSON.stringify
does not support BigInts, a common suggestion is to patch toJSON
into its prototype or use a replacer function to the likes of (k, v) => typeof v === 'bigint' ? v.toString() : v
. The problem is, this stringifies BigInts as strings and not numbers { foo: 123n }
becomes { "foo": "123" }
instead of { "foo": 123 }
.
I have a requirement to produce a payload for an API that expects a number, and that number can exceed the largest safe integer possible in JS. Is there any way to do that, besides building the string myself (or stripping out the quotes afterwards)?
2
Answers
I would add some kind of unique token to the bigint string, then strip the quotes and token as a whole after stringify:
It depends on what you are looking for, Javascript cannot natively parse BigInt in JSON, but there are ways to work around that with altering
JSON.parse()
from the MDN BigInt Documentation.If your number is less than 2^53-1, then using
Number(big_int)
would be ideal. You can test for this with:If you really need to have the BigInt as in numeric form without the double quotes this is a quick and dirty way using string replacement. It replaces and stores BigInt values in a list before
JSON.stringify()
and then replacing the stub values with the numeric BigInt: