Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to omit empty lists using aeson deriveJSON?

Tags:

haskell

aeson

Using the aeson deriveJSON it is easily to omit Nothing values, e.g.:

data Person = 
  Person {
    ssn :: Maybe Text,
    phone :: [Text]
  }

$(deriveJSON defaultOptions{omitNothingFields=True} ''Person)

I would like to also omit empty lists in order to keep the JSON compact. Is there a general to omit empty lists using deriveJSON, without hand rolling instances?

like image 376
user868458 Avatar asked Jan 25 '14 01:01

user868458


1 Answers

I believe you cannot currently do that.

I guess it follows the philosophy that the structure of the object should roughly align with the type; from that view point, having {... phone: [] ...} or even {... phone: null ...} for non-existant fields is "more typed" than leaving them out of the object.

If the reason you want to keep the JSON "compact" is not for elegance, but e.g. bandwidth reasons, gzip or things like JSONH might achieve almost the same savings transparently, without you having to change the structure of your objects.

like image 86
nh2 Avatar answered Nov 02 '22 14:11

nh2