I'm looking for a way to force JSON.stringify
to always print BigInt
s without complaining.
I know it's non-standard, I know there's a package for that in pure JavaScript; but it doesn't fit my needs. I even know a fix in raw JavaScript by setting BigInt.prototype.toJSON
. What I need is some way to override the normal JSON.stringify
function globally in my TypeScript code.
I had found the following code, a year or so ago:
declare global
{
interface BigIntConstructor
{
toJSON:()=>BigInt;
}
}
BigInt.toJSON = function() { return this.toString(); };
on some web page I can't manage to find again. It used to work in another project of mine, but it doesn't seem to work any more. I have no idea why.
No matter what I do to the lines above, if I try to print a JSON containing a BigInt, I get: TypeError: Do not know how to serialize a BigInt
.
Any help is appreciated - many thanks in advance.
You could use the replacer
argument for JSON.stringify
like this:
const obj = {
foo: 'abc',
bar: 781,
qux: 9n
}
JSON.stringify(obj, (_, v) => typeof v === 'bigint' ? v.toString() : v)
This is what you looking for:
BigInt.prototype.toJSON = function() { return this.toString() }
https://github.com/GoogleChromeLabs/jsbi/issues/30#issuecomment-953187833
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With