TypeScript: serialize BigInt in JSON

Viewed 5117

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.

3 Answers

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)

I needed to get JSON.stringify to work in one of the dependencies, so I couldn't use the above answer. Instead, I created a patch.js file:

BigInt.prototype.toJSON = function() {
    return this.toString()
} 

Then at the beginning of my TypeScript source I added:

require('patch.js')

After that, JSON.stringify could handle BigInts without any problems.

Related