top | item 38732294

(no title)

shrew | 2 years ago

I understand your point and I can’t deny that Javascript continues to introduce weird, silent failures and quirks even today when everything is a bit more thought out than “the bad old days”.

But I think in the case of JSON.stringify it’s more about use case. 99% of the time, users of this method are taking some data and serialising it to a JSON compliant form to send to the server. JSON doesn’t support functions, or complex objects like a Date, so I tend to think it’s a reasonable default that functions disappear and Date’s are converted to an ISO standard. To insist that every single user runs a preparation step that strips out unserialisability data and chooses how to handle Date objects sounds laborious, error prone, and ripe for another npm dependency everyone suddenly normalises for every project.

Maybe a “strict mode” of some sort where you could have it throw on anything for cases where you need to guarantee everything is being sent?

OTOH, I have to concede that while this method has silent failures, they then implemented JSON.parse to throw at the slightest issue. So I have to admit there’s consistency even within the API.

discuss

order

easyThrowaway|2 years ago

I guess there's some good reason nobody ever did it, but what about throwing an UnhandledType kind of error and letting the catch() decide how to deal with the object in question?

usrusr|2 years ago

On top of the compatibility issue mentioned in sibling comment, the existing behavior also matches the principle of keeping simple things simple without making complicated things impossible. If you want stringify with a check for unhandled elements, that's easily specified in a replacer (that does not really replace).

You might prefer some well established standard implementation over ad hoc roll your own, but that's a discussion about npm culture, not about stringify.

whatevaa|2 years ago

Browser care about compatibility a lot, the ship to change this behavior has shipped a long time ago.

Levitz|2 years ago

>and ripe for another npm dependency everyone suddenly normalises for every project

Now now, it's only 1M weekly downloads: https://www.npmjs.com/package/superjson

shrew|2 years ago

Interesting, I’ve never seen this, thanks!

The problem I see with this is that whatever you’re sending this to must have knowledge of the meta information superjson produces, so at that point you’re investing in it as a wrapper library. The fact you can extend the types it serialises also complicates things and means the receiver needs further implementation specific knowledge.

I think in my original comment, I was imagining a world where JSON.serialize threw errors on unknown types and we needed a wrapper just get basic JSON out of it.