Elm: Decode fields that might be absent in JSON

Jigar Gosar
Aug 23, 2017 · 2 min read

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

The Functional Programmer

Pragmatic Functional Programming For The Web

)

Jigar Gosar

Written by

Eternally Curious. Life Hacker. Programming Addict.

The Functional Programmer

Pragmatic Functional Programming For The Web

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade