windwarrior windwarrior - 5 months ago 28
JSON Question

Data.Aeson encoding optional keys

I have the following problem, I have a JSON format with optional keys that I need to generate from my haskell code.

Lets make an example

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics
import Data.Aeson

data Person = {
name :: String,
shoeSize :: Maybe Int,
favoriteColor :: Maybe String,
favoriteFood :: Maybe StringC
} deriving (show, eq, generic)

instance ToJSON Person -- Generic instance


now, if I try encoding a Person without a shoesize I still get a key "shoeSize" set to null, what is the Aeson way of making keys optional in encoding

edit, example of an encode

encode $ Person "windwarrior" Nothing "green" Nothing


should result in

{"name":"windwarrior", "favoriteColor":"green"}

Answer

Use TemplateHaskell to derive the ToJSON instance instead of Generic. The TH functions optionally take an Options which has the omitNothingFields option.

Comments