aeson-pretty
aeson-pretty copied to clipboard
[feature] Optionally suppress keys with null values
Apparently, such a feature is available in the Data.Aeson.TH
module (see omitNothingFields
), but that module requires that TemplateHaskell
be enabled.
This should be done in the ToJSON
instance.
omitNothingFields
exists for TemplateHaskell and DeriveGeneric. Or if you write your own ToJSON
instance, you can do it there.
I do now see omitNothingFields
in the Data.Aeson.Types
module in addition to the Data.Aeson.TH
module.
However, I currently have over 50 records (with this number expected to grow) which require serialization to JSON, so the cost of additional per-record boilerplate is high.
With my modification to aeson-pretty
to suppress nulls, I am able to get by with only a single, short line per record to declare each as an instance of ToJson
:
instance ToJSON MyModule.MyRecord
Unless I am missing something, without having aeson-pretty
handle it, the per-record boilerplate increases to this:
instance ToJSON MyModule.MyRecord where
toJSON = genericToJSON defaultOptions { omitNothingFields = True }
Although this is a 100% increase in lines for me (more in terms of tokens), perhaps this amount of boilerplate doesn't earn me any sympathy.
Wouldn't it make more sense to write a function
removeNullValues :: Value -> Value
and then encode your value with encodePretty . removeNullValues . toJSON
instead of encodePretty
?
Wouldn't it make more sense to write a function
The stripNulls
example from aeson-extras
does exactly this, https://github.com/phadej/aeson-extra/pull/57.