Search code examples
elmjson-deserialization

elm: decode json that contains a json array


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


Solution

  • 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":

    import Json.Decode exposing (..)
    
    decodeErrorResponse : Decoder ErrorResponse
    decodeErrorResponse =
        map ErrorResponse
            (field "ValidationErrors" (list decodeValidationResults))
    

    One bit of advice: You can use Json.Decode.field instead of Json.Decode.at when there is only a single level. You can rewrite decodeValidationResults as this:

    decodeValidationResults : Decoder ValidationResult
    decodeValidationResults =
      map2 ValidationResult
        (field "Parameter" string)
        (field "ErrorMessage" string)