Hacker News new | ask | show | jobs
by Lx1oG-AWb6h_ZG0 1943 days ago
> Using JSON.stringify() with any BigInt value will raise a TypeError as BigInt values aren't serialized in JSON by default. However, you can implement your own toJSON method if needed

Sorry, why exactly can’t they also define the json.parse/stringify behavior of bigints? JSON was initially derived from JavaScript, so it seems a bit weird that a new ES standard can’t interoperate with json

4 comments

I wondered about JSON serialization too - lots of discussion on this here https://github.com/tc39/proposal-bigint/issues/24 and here https://github.com/tc39/proposal-bigint/issues/162. After 15 minutes down that rabbit-hole, the answer is "it's complicated".
> Sorry, why exactly can’t they also define the json.parse/stringify behavior of bigints?

Because every construct in JSON already has a defined way that it is parsed into JS and incorporating BigInt into that by default would break backwards compatibility of JS’s JSON handling.

Interop concerns make the right JSON serialization very application dependent, too.

I’m sure they could make stringify work, since numbers in JSON can be arbitrarily large. But parsing JSON and having it return BigInt instead of Number just isn’t going to be able to work by default. I guess because of this, making stringify work without parse support just isn’t desirable.
Where do you read numbers can be arbitrarily large? I thought it was limited to javascript numbers.
> Where do you read numbers can be arbitrarily large?

RFC 8259, Section 6, specifies unlimited number of digits for the integer and fraction parts, but allows implementations to have size and precision constraints.

> I thought it was limited to javascript numbers.

It suggest that IEEE754 binary64, because it is widely available and supported, should generally be safely usable (which happens to be exactly JavaScript numbers) but it does not limit JSON numbers to that range/precision.

Because bigints aren't part of the json spec? Like they said you create your own toJSON like: 'BigInt.prototype.toJSON = function() { return this.toString(); };' if you want to bend the spec.
> Because bigints aren't part of the json spec?

Arbitrarily sized numbers (with no guarantee on supported range or precision in processors) are part of the spec, the problem is JS already serializes/deserializes them as Number and any change would break backwards compatibility.