8

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?

user868458
  • 81
  • 2
  • 6
    You could perhaps change the type to `Maybe (NonEmptyList a)` and write an appropriate To/FromJSON setup for that. I think it more clearly encodes the kind of information you're trying to convey, perhaps. – J. Abrahamson Jan 25 '14 at 03:15

1 Answers1

2

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.

nh2
  • 24,526
  • 11
  • 79
  • 128