Search code examples
jsontypescriptglobalbigint

TypeScript: serialize BigInt in JSON


I'm looking for a way to force JSON.stringify to always print BigInts 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.


Solution

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