Reputation: 2684
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
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