Elm: Decode fields that might be absent in JSON

Jigar Gosar
The Functional Programmer
2 min readAug 23, 2017

How to Decode JSON in Elm Part 2

Part1

Imports

import Json.Decode as D exposing (Decoder)
import Json.Decode.Pipeline as D
import Json.Encode as E exposing (Value)

Record

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

Decoder — All fields required

If any of the fields are missing or have invalid type, following decoder will fail.

userDecoder : Decoder User
userDecoder =
D.succeed User
|> D.required "name" D.string
|> D.required "age" D.int

Success Example:

> D.decodeString userDecoder """{"name": "Jack", "age": 25 }"""
Ok { name = "Jack", age = 25 } : Result.Result String Repl.User

Failure Example: age field missing

> D.decodeString userDecoder """{"name": "Jack"}"""
Err "Expecting an object with a field named `age` but instead got: {\"name\":\"Jack\"}"
: Result.Result String Repl.User

Decoder — Age optional

if age feild is missing, then following decoder will default its value to one specified. (3rd argument to D.optional function)

userDecoder : Decoder User
userDecoder =
D.succeed User
|> D.required "name" D.string
|> D.optional "age" D.int 0

Success Example: age field missing

> D.decodeString userDecoder """{"name": "Jack"}"""
Ok { name = "Jack", age = 0 } : Result.Result String Repl.User

Success Example: age field present

> D.decodeString userDecoder """{"name": "Jack", "age": 25 }"""
Ok { name = "Jack", age = 25 } : Result.Result String Repl.User

CAUTION

If the optional field is present then it will be decoded using specified decoder, which may result in failure.

Failure Example: age field present, but not int compatable

> D.decodeString userDecoder """{"name": "Jack", "age": "25" }"""
Err "I ran into a `fail` decoder: I ran into the following problems:\n\nExpecting an Int but instead got: \"25\"\nExpecting null but instead got: \"25\""
: Result.Result String Repl.User

Complete example

--

--