flightcontrolhq / superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
https://www.flightcontrol.dev?ref=superjson
MIT License
4.01k stars 87 forks source link

Backwards compatibility with JSON #282

Closed NMinhNguyen closed 9 months ago

NMinhNguyen commented 9 months ago

Would it be possible to use superjson as a drop-in replacement for JSON, especially where you have some existing JSON (e.g. persisted), and you’d want it to be deserialised by superjson? Without native support for this, my worry is that consumers would either need to migrate all their JSON blobs to the superjson format, or write a custom serialise/deserialise function on top (e.g. with a top-level key such as "__superjson__": "v1" to know whether to parse via JSON.parse or superjson). In other words, I’d expect superjson.parse(JSON.stringify(value)) to work - then it would truly be a superset of JSON.

Skn0tt commented 9 months ago

Hey! The "SuperSet of JSON" claim refers to the fact that it supports a superset of the datatypes that JSON support, not to its specific output format.

write a custom serialise/deserialise function on top

That's what I'd recommend to do. If you're doing a migration, chances are that you'll have specific logic around it already, and that should contain the logic around using SuperJSON / JSON.

If we put this logic into SuperJSON itself, it would make it more complex to reason about, for no real advantage.

Here's a function that could work for the migration:

function parseJSONorSuperJSON(value: string) {
   const result = JSON.parse(value)
   return "json" in result
     ? SuperJSON.deserialize(result)
     : result
}