Elm: Decode fields that might be absent in JSON
Aug 23, 2017 · 2 min read
How to Decode JSON in Elm Part 2
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.intSuccess Example:
> D.decodeString userDecoder """{"name": "Jack", "age": 25 }"""
Ok { name = "Jack", age = 25 } : Result.Result String Repl.UserFailure 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.UserDecoder — 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 0Success Example: age field missing
> D.decodeString userDecoder """{"name": "Jack"}"""
Ok { name = "Jack", age = 0 } : Result.Result String Repl.UserSuccess Example: age field present
> D.decodeString userDecoder """{"name": "Jack", "age": 25 }"""
Ok { name = "Jack", age = 25 } : Result.Result String Repl.UserCAUTION
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
