How to Decode JSON in Elm Part 1

Jigar Gosar
The Functional Programmer
2 min readJan 8, 2017

Easily decode any JSON to Elm type alias, union type, singleton type constructors. And any nested combination of these.

In Elm, JSON encoding and decoding is quite easy as opposed to what people think. The main problem is lack of good examples. I have struggled a lot, and have found answers to almost all of my conscerns. Thanks to awesome Elm Community.

Following is what I intend to cover in this series

  • Decode JSON objects to Elm Records (current article)
  • Decode fields that might be absent in JSON
  • Decode fields of type Maybe
  • Decode simple Union Type
  • Decode Single Constructor Union Type
  • Decode Parameterised UnionType
  • Decode any combination of above
  • Encode any combination of above
  • Strategies to deal with changing shape of types when our application grows
  • Using Versions to maintain backward compatibility
  • Strategies to handle decoding errors

Decoding JSON objects to Elm Records

We can send Javascript objects directly over ports. There is no need to JSON encode them. Once received we can use Json.Decode.decodeValue

port onSomeEvent : (D.Value -> msg) -> Sub msg

Let’s define type alias for SomeEvent

type alias SomeEvent =
{ name : String
, age : Int
}

Now let’s write a decoder for it

someEventDecoder = 
D.succeed SomeEvent
|> DP.required "name" D.string
|> DP.required "age" D.int

As a convention, I rarely import any module directly. Using namespace prefix is prefered. So what is D and DP?

import Json.Encode as E
import Json.Decode as D
import Json.Decode.Pipeline as DP

Using the pipeline library allows to use the required function with |> operator.

Now to get the result of decoding we can simply write

decodeSomeEvent: D.Value -> Result String SomeEvent
decodeSomeEvent encoded = someEventDecoder |> D.decodeValue encoded

And we are done, well almost. Now it is up to us how to handle the failure case.

Until next time. Enjoy Elm!

P.S. With enough support and encouragement, I would like to write a tool that will automate this process completely.

I love Elm, and would like to help anyone who is stuck because of lack of tutorials or examples. Feel free to write to me.

--

--