Since JSON values are not known until runtime there is no way of checking them at compile time. This means that there is a possibility a decoding operation can not be successfully completed.
In that case there are two possible solutions:
Maybe valueIn this module these two options are represented by require and
attempt.
require can fail if the decoding can not be completed.attempt will never fail. It always decodes to a Maybe value.Decode nested fields. Works the same as require but on nested fieds.
blogPost : Decoder BlogPost
blogPost =
require "id" Decode.int <| \id ->
require "title" Decode.string <| \title ->
requireAt ["author", "name"] Decode.string <| \authorName ->
Decode.succeed
{ id = id
, title = title
, author = authorName
}Decode optional fields.
Always decodes to a Maybe value and never fails.
Example:
person : Decoder Person
person =
require "name" Decode.string <| \name ->
attempt "weight" Decode.int <| \maybeWeight ->
Decode.succeed
{ name = name
, weight = maybeWeight
}In this example the maybeWeight value will be Nothing if:
weight field is missing.weight field is not an Int.In this case there is no difference between a field being null or missing.
If a field must exist but can be null, use require and Decode.maybe instead:
require "field" (Decode.maybe Decode.string) <| \field ->Decode optional nested fields. Works the same way as attempt but on nested fields.
Decode required fields.
Example:
In this example the decoder will fail if:
"id"or"name"are missing. If the object contains other fields they are ignored and will not cause the decoder to fail."id"is not anInt."name"is not aString.