JSON support for BigInt in Chrome/V8

T.J. Crowder tj.crowder at farsightsoftware.com
Thu Jul 26 16:51:18 UTC 2018


Not having JSON support for BigInt is a big problem. But the fact exists
that JSON does not cover everything. It doesn't cover Dates, Maps, Sets,
Symbols...

Until/unless the successor to JSON (whatever it may be) is created and
adopted, a process that will take years, let's take a pragmatic approach
similar to the pragmatic approach taken in relation to Dates: Abuse a
string.

```js
BigInt.prototype.toJSON = function() {
    return `/BigInt(${this.toString()})/`;
};
```

Then this:

```js
console.log(JSON.stringify({n:10n}));
```

outputs

```
{"n":"/BigInt(10)/"}
```

Do I like it? Not even a little bit. But as a pragmatic way forward,
providing `toJSON` on BigInt's prototype and having it produce something
along these lines seems like Better Than Nothing™. Date's `toJSON` produces
a string in a readily-recognized format, after all. I'd also suggest
`BigInt.fromJSON` which validated and parsed the string in that format.

This would put us where Dates are now, but without competing standards for
them (ISO string vs.` /Date(epochval)/`).

-- T.J. Crowder
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180726/b2ae0a67/attachment-0001.html>


More information about the es-discuss mailing list