cynkra / constructive

Display Idiomatic Code to Construct Most R Objects
https://cynkra.github.io/constructive
Other
111 stars 6 forks source link

json #179

Open moodymudskipper opened 1 year ago

moodymudskipper commented 1 year ago

Useful for #177 and probably other use cases

define json objects from vectors, lists or data frame so they print prettier, using jsonlite::toJSON()

This would also allow using the data arg of construct().

We should keep the other parameters to provide flexibility re the json format

We might detect from the format if we should use serializeJSON()

A simple way to be to test the round trip fromJSON toJSON (resp with serialize if it has the relevant structure), if it works apply constructor, otherwise fall back to character (current).

moodymudskipper commented 1 year ago

json is actually awkwards because serialisation cares about attribute order while the rest of R, including identical() and waldo::compare() do not. And things like subsetting will shuffle the attribute order: https://twitter.com/antoine_fabri/status/1662909266607366144

In principle we could add to constructors an argument to make sure we keep attributes in order, and serialisation functions in constructors would force it, but in practice this would build very awkward code, so I'm tempted to sweep this one under the rug.

Another solution is to provide the constructor for json but have it default on "atomic" so the user actually has to opt in to use it.

Or we force the list constructor instead of data frame/tibble/data.table for its input