aeson-pretty icon indicating copy to clipboard operation
aeson-pretty copied to clipboard

[feature] Optionally suppress keys with null values

Open kostmo opened this issue 8 years ago • 4 comments

Apparently, such a feature is available in the Data.Aeson.TH module (see omitNothingFields), but that module requires that TemplateHaskell be enabled.

kostmo avatar May 22 '16 21:05 kostmo

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.

informatikr avatar May 23 '16 09:05 informatikr

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.

kostmo avatar May 24 '16 06:05 kostmo

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?

chris-martin avatar Feb 28 '18 00:02 chris-martin

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.

philderbeast avatar Jun 05 '23 16:06 philderbeast