Remix.run Logo
VanCoding 5 hours ago

That's not what I mean. Even though it is serializable, it's still not the same when you serialize/deserialize it.

For example `JSON.parse(JSON.stringify(Temporal.PlainYearMonth.from({year:2026,month:1}))).subtract({ years: 1})` won't work, because it misses the prototype and is no longer an instance of Temporal.PlainYearMonth.

This is problematic if you use tRPC for example.

flyingmeteor 5 hours ago | parent | next [-]

You would need to use the `reviver` parameter of `JSON.parse()` to revive your date strings to Temporal objects. As others have said, it's a simple `Temporal.from()`

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

Bratmon 3 hours ago | parent | next [-]

Having to provide a complete schema of your json everywhere your json gets parsed negates the advantages of json.

true_religion 2 hours ago | parent | next [-]

The main advantage of json is that it’s human readable and writable. Beyond that, it has no notion of user created data types so anyone using it has to do custom unmarshalling to get a type apart from sting, number, dict and list.

hueho an hour ago | parent | prev [-]

Most JSON libraries in typed languages require this for data binding to complex types though.

cyral 4 hours ago | parent | prev [-]

I've been doing this for so long and never knew there was a reviver param, thanks - that is super useful.

rimunroe 4 hours ago | parent | prev | next [-]

> For example `JSON.parse(JSON.stringify(Temporal.PlainYearMonth.from({year:2026,month:1}))).subtract({ years: 1})` won't work, because it misses the prototype and is no longer an instance of Temporal.PlainYearMonth.

I don't know if I'm missing something, but that's exactly how I'd expect it to compose. Does the following do what you wanted your snippet to do?

  Temporal.PlainYearMonth.from(JSON.parse(JSON.stringify(Temporal.PlainYearMonth.from({year:2026,month:1}))))
JSON.stringify and JSON.parse should not be viewed as strict inverses of each other. `JSON.parse(JSON.stringify(x)) = x` is only true for a for a small category of values. That category is even smaller if parsing is happening in a different place than stringification because JSON doesn't specify runtime characteristics. This can lead to things like JSON parsing incorrect in JS because they're too large for JS to represent as a number.
gowld 5 hours ago | parent | prev [-]

Would a plain data object be an instance of PlainYearMonth?

If not, that regardless of being plain data or a serialized object with functions, you'd still need to convert it to the type you want.