Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 506
Tristan Duquesne Avatar asked Dec 31 '22 18:12

Tristan Duquesne


2 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)
like image 70
Alex Chashin Avatar answered Jan 12 '23 01:01

Alex Chashin


This is what you looking for:

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

https://github.com/GoogleChromeLabs/jsbi/issues/30#issuecomment-953187833

like image 32
Andrey Madzhidov Avatar answered Jan 12 '23 03:01

Andrey Madzhidov