This module helps you create a Json Decoder that will never fail. This is useful when you want to decode a record but not fail if something is wrong.
This could of course be achieved by defaulting if the normal decoder fails:
Json.Decode.decodeValue recordDecoder value
|> Result.withDefault defaultRecord
The problem with this approach is that if one field is faulty the whole record will be defaulted. In some cases you want to decode everything possible and only use default for fields that couldn't be decoded.
This decoder will always succeed with a value and a list of errors.
import Json.Decode as Decode
decoder =
at ["field1"] Decode.string "Default 1" <| \value1 ->
at ["field2"] Decode.string "Default 2" <| \value2 ->
return
{ field1 = value1
, field2 = value2
}
Running the decoder with this Json value:
{
"field1": "Hello",
"field2": null
}
Will result in the record:
{ field1 = "Hello"
, field2 = "Default 2"
}
and a list of Error
:
[ { path = ["field2"]
, error = Field "field2" (Failure ("Expecting a STRING") <internals>)
}
]
A decoder that never fails.
at : List String -> JsonDecoder a -> a -> (a -> FlagsDecoder b) -> FlagsDecoder b
Decode a field with an optional value
at <path> <decoder> <default value> <continuation>
at ["field1"] Decode.string "1" <| \value1 ->
at ["field2"] Decode.int 2 <| \value2 ->
return
{ field1 = value1
, field2 = value2
}
return : a -> FlagsDecoder a
Return a value from your decoder.
{ path : List String
, error : Json.Decode.Error
}
A decode error.
decodeString : FlagsDecoder a -> String -> ( List Error, a )
Decode a json string
decodeValue : FlagsDecoder a -> Json.Decode.Value -> ( List Error, a )
Decode a Json value