Aeson with types that have lots of "maybes"

Aeson is a real joy to use once you get into the swing of things, but there are some patterns out there that end-users are left to discover for themselves. One of those is how to deal with data that has a lot of instances of the Maybe type.

I’ve refactored and cleaned up this code, look at the do-over.

See here for the new article

First, a trivial example:

Okay, not bad! For other simpler examples also see:

But given a less-nice data-type like:

This is a bit of a mess. There’s uncertainty slapped all over the data-type. Only simpleQueryStringQuery of type QueryString is guaranteed to exist. Everything else might be Nothing.

Rather than break out these cases individually, I started using a pattern combining catMaybes and a function I (inadvisedly) named mField.

First, an aside. How is catMaybes even possible? We’re conflating the possibility of [Nothing, Nothing, ...] with the empty list case []. Anything Just a is kept.

Okay, so what does our final instance look like?

Want to see more? - Check out Bloodhound, the library this code is from

I know this site is a bit of a disaster zone, but if you like my writing or think you could learn something useful from me, please take a look at the Haskell book I've been writing. There's a free sample available too!