Mark Karavan
Mark Karavan

Reputation: 2684

Json.Decode.Pipeline on a list (elm 0.18)

I have a type alias with a nested list that I want to parse with Json.Decode.Pipeline.

import Json.Decode as Decode exposing (..)
import Json.Encode as Encode exposing (..)
import Json.Decode.Pipeline as Pipeline exposing (decode, required)

type alias Student =
    { name : String
    , age : Int
    }

type alias CollegeClass =
    { courseId : Int
    , title : String
    , teacher : String
    , students : List Student
    }

collegeClassDecoder : Decoder CollegeClass
collegeClassDecoder =
    decode CollegeClass
        |> Pipeline.required "courseId" Decode.int
        |> Pipeline.required "title" Decode.string
        |> Pipeline.required "teacher" Decode.string
        |> -- what goes here?

How does this work?

Upvotes: 5

Views: 915

Answers (1)

pdoherty926
pdoherty926

Reputation: 10399

You'll need to pass a decoder to Decode.list. In your case, it'll be a custom one based on the shape of your Student type.

This hasn't been tested, but something like the following should work:

studentDecoder =
    decode Student
        |> required "name" Decode.string
        |> required "age" Decode.int

collegeClassDecoder : Decoder CollegeClass
collegeClassDecoder =
    decode CollegeClass
        |> Pipeline.required "courseId" Decode.int
        |> Pipeline.required "title" Decode.string
        |> Pipeline.required "teacher" Decode.string
        |> Pipeline.required "students" (Decode.list studentDecoder)

See this post on writing custom flag decoders which should be instructive.

Upvotes: 7

Related Questions