3 ms·
It may look like for simple use cases the JSON one works. But one thing not included in this page is that there are things it just doesn't serialize, even when
by WirelessGigabit 4y ago
It may look like for simple use cases the JSON one works.
But one thing not included in this page is that there are things it just doesn't serialize, even when it's actual data:
const native = { number: Number.POSITIVE_INFINITY };
const cloned = JSON.parse(JSON.stringify(native));
// unlike NaN, we can compare Number.POSITIVE_INFINITY to itself
console.log(native.number === native.number);
// but it doesn't serialize
console.log(native.number === cloned.number);
console.log(cloned);
Yields
true
false
{number: null}
Oops.
- kevingadd 4y agoThis is because inf and nan were left out of the json spec, right? Great format
- Waterluvian 4y agoRight because the spec is not IEEE 754. JSON numbers are not floats. They’re numbers with as many decimal points as you want. It’s up to the serializer/deserializer to decide how to handle them.
- zarzavat 4y agoThe clear intention of the JSON spec is that JSON numbers should deserialise to doubles, and this is how every decoder that I've ever seen handles it. The first decoder was the JS eval() function, so JSON was clearly intended to be a subset of JS. Ambiguity in the spec is not a licence to deviate from JS semantics, it just means that the spec is poorly written.
- Waterluvian 4y agoIt was intentionally written to be very simple and achieved that goal. If your opinion is that that’s a poor choice, sure. But that’s an opinion, not a fact. Specifying a specific float format would cripple an interchange format and I think that would be a mistake. The intention here is to allow each origin and destination to decide how to fit the generic data into their representation formats. The spec is not ambiguous. And a spec is a spec is a spec. You can implement it or not. But you can’t just decide “Enh… they didn’t mean it like that so it’s wrong to satisfy the spec. You should really satisfy it wrongly.”