So I need to decode a json
that contains a json array
in elm
. Here is my model:
type alias ValidationResult =
{ parameter : String
, errorMessage : String
}
type alias ErrorResponse =
{ validationErrors : List ValidationResult }
And here is an example of the json
:
{"ValidationErrors": [{"Parameter": "param1","ErrorMessage": "message 1"},{"Parameter": "param2","ErrorMessage": "error message 2"}]}
I've tried to create a ValidationResult
decoder, like:
decodeValidationResults : Decoder ValidationResult
decodeValidationResults =
map2 ValidationResult
(at [ "Parameter" ] Json.Decode.string)
(at [ "ErrorMessage" ] Json.Decode.string)
But I don't know how to proceed further.
I am using elm
0.18
You are almost there! You just need a decoder that decodes the
ErrorResponse
type. To do so, create another decoder that uses a list of the decoder you've already created, assuming the field name is"ValidationErrors"
:One bit of advice: You can use
Json.Decode.field
instead ofJson.Decode.at
when there is only a single level. You can rewritedecodeValidationResults
as this: