Haskell - Encoding and Decoding JSON with Aeson

Posted on September 24, 2019

There are a lot of blog posts and tutorial about encoding/decoding JSON with aeson. Even the library is pretty good at teaching how to do this. The tutorial I always go back to is Artyom Kazak’s tutorial. They talk about lots of different techniques on how to decode and encode json on different cases.

Let’s start off with the basics by deriving instances of FromJSON and ToJSON manually.

With FromJSON and ToJSON instances we can now consume json of this shape:

As you can see when the type has more fields that also means that we have to type out all those fields. Your fingers are going to fall off by the time you are done with your app.

One solution to minimize the boilerplate is by using Generics

If we use {-# LANGUAGE DeriveAnyClass #-} pragma we can do this.

DeriveAnyClass and GenerlizedNewTypeDeriving

If we have both of these language extensions enabled, ghc will complain about derivation being ambigious. To get around this use {-# LANGUAGE DerivingStrategies #-} language extension.

If we don’t need to do anything with the field name this will suffice. However, our field name is title not bookTitle so we have to do a little modification to the field names by doing the following

Here’s a reference to defaultOptions. In the code above we’re doing a record update. That means it’s gonna drop 4 characters from the beginning and then camel case it.

Nullable Fields

When it comes to nullable fields, Generics will automatically use this operator (.:?) on fields that are Maybes, which will use Nothing if the field is null or missing.

Optional Fields

For optional fields we have to go back to manually deriving ToJSON and FromJSON manually.

Sum Types

or if we we can decide based on the format

The same with product types we can also use Generics and some language extensions to derive FromJSON and ToJSON instance

These are the usual day to day techniques of encoding/decoding json data that I use.