Search code examples
jsonfrontendelmdecoder

Elm: Decode a JSON array with a single element into a string


had a look for something like this, but can't find the exact issue.

I have a JSON back from server side validation that looks like:

{ 
  "field": ["field-name"], 
  "messages":["message","message"]
}

What I would like to do is decode it into an elm record like

{ field: String, messages: List String }

However, I'm having trouble with the err, field field. I'm having trouble turning a single element JSON array into just a string of that element.

Is it even possible with Decode, or am I better of Decoding it into a List and then just grabbing the head from the list.

This is what I have for the decode:

valErrorDecoder : Decode.Decoder ValError
valErrorDecoder =
decode ValError
    |> required "field" (Decode.list Decode.string)
    |> required "messages" (Decode.list Decode.string)

Thanks for any help!


Solution

  • Try Decode.index, that should do the trick.

    valErrorDecoder : Decode.Decoder ValError
    valErrorDecoder =
    decode ValError
        |> required "field" (Decode.index 0 Decode.string)
        |> required "messages" (Decode.list Decode.string)