James
James

Reputation: 4052

Elm Simple JSON List Decoding

I have a simple structure that I need to be able to decode, but I'm having problems.

My API response looks like this:

[{"userId":70, "otherField":1, ...},
 {"userId":70, "otherField":1, ...},    
 {"userId":71, "otherField":1, ...}]

I'm trying to decode it as follows:

type alias SessionResponse =
    { sessions : List Session
    }


type alias Session =
    { userId : Int
    }


decodeSessionResponse : Decoder (List Session)
decodeSessionResponse =
    decode Session
        |> list decodeSession -- Gives an Error


decodeSession : Decoder Session
decodeSession =
    decode Session
        |> required "userId" int

The error message I'm seeing is:

The right side of (|>) is causing a type mismatch.

(|>) is expecting the right side to be a:

Decoder (Int -> Session) -> Decoder (List Session)

But the right side is:

Decoder (List Session)

 It looks like a function needs 1 more argument.

How can I fix this error?

Upvotes: 2

Views: 168

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36385

There are a few ways to approach this based on what you are trying to do.

Edit: Based on your comment and a re-reading of your question:

You pointed out that the API response is an array of sessions, which means you can just use Json.Decode.map to map a list Session to a SessionResponse:

decodeSessionResponse : Decoder SessionResponse
decodeSessionResponse =
     map SessionResponse (list decodeSession)

Original Answer:

If you want to match the type signature of decodeSessionResponse and return a Decoder (List Session), then you can simply return list decodeSession.

decodeSessionResponse : Decoder (List Session)
decodeSessionResponse =
    list decodeSession

What I suspect is that you would rather return a Decoder SessionResponse, which could be defined as such:

decodeSessionResponse : Decoder SessionResponse
decodeSessionResponse =
    decode SessionResponse
        |> required "sessions" (list decodeSession)   

Upvotes: 3

Related Questions