5 Common JSON Decoders

You’ve learned the basics of decoding JSON in Elm and are comfortable converting
JSON into records. However, real life has a tendency to give you tricky JSON
to work with that doesn’t fit neatly with this approach.

Here are five scenarios I commonly run into and how to decode them.

In all these examples, you can assume the decode library has been imported like:

Oftentimes you will want to express a limited set of values as a union type:

typeDirection=North|South|East|West

JSON doesn’t support values like this and will probably send these values down
as strings or integers. We’ll need to decode this in two steps: first decode the
string, and then turn the string into a direction. Because we might get an
invalid string value, we need to handle errors too.

If you are parsing union types from strings elsewhere in your code, you may want
to separate the parsing from the decoding. Write a regular parsing function that
returns a Result and write a function that can convert that Result into a
Decoder.

Sometimes your JSON can be in multiple shapes and you’d like to decode it
differently based on the shape. Here we have a payload that may or may not have
an email depending on whether the user is signed in.

Json.Decode.oneOf allows you to specify a list of possible decoders. It will
go through the list in order and use the first one that can successfully decode
the JSON. Finally we can write a userDecoder that looks like:

The JSON for both of these would have the same shape so we can’t use oneOf.
Instead, we’ll have to decode based on the values of some of the fields in the
JSON. In this particular case, the backend team have helpfully added a role
field to the JSON that will be either "regular" or "admin":