Feature Request: Enable the default record serialization to be customized
thurn opened this issue · 1 comments
Since an EncodeJson instance was added for Records (#37), it is not possible to customize the default serialization of records without resorting to newtypes for everything. This is somewhat inconvenient for simple transformations.
It would be cool if I could pass a function to apply custom processing logic to the output JSON. In my case, I would like to be able to capitalize the names of the keys. Post-processing for keys would be a good first step, since I imagine it's fairly common to need to transform them into other formats (e.g. underscore separated).
@thurn I think that's outside the scope of this library, as it's highly convenient to be able to have a default instance for records, but there are some other ways that you can do what you're looking for without requiring changes here.
Specifically, you can manipulate the resulting Json directly using functions from purescript-argonaut-core like caseJson, or the helper functions in purescript-argonaut-traversals, which are meant specifically for manipulating Json without much boilerplate. There are also libraries like purescript-tolerant-argonaut which might do what you're looking for.
I'm aware that argonaut-traversals is not well-documented. If you feel more comfortable working with an Object Json where you can capitalize all the keys using functions from purescript-foreign-object, then you can use just this prism to get that object so you can process it: https://github.com/purescript-contrib/purescript-argonaut-traversals/blob/6613254947961686341eaa1ed23886c9d2587d93/src/Data/Argonaut/Prisms.purs#L23
For example:
process :: Json -> Json
process json = case preview _Object json of
Nothing -> json
Just object -> do
let processed = (...process keys)
encodeJson processed -- turn the object back into `Json`