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?
Elm provides three other decoders for translating primitive JSON types to Elm values: int, float, and bool. Here are some examples showing them in action: JSON supports the following data types:
Elm provides three other decoders for translating primitive JSON types to Elm values: int, float, and bool. Here are some examples showing them in action:
For JSON, the server uses application/json as the Content-Type header’s value. Whereas, for string it uses text/plain. Elm provides a package called elm/json which includes modules for encoding and decoding JSON values.
The decodeString function is the one that does the actual decoding. It first parses the raw string into JSON and then applies the string decoder to translate that JSON into an Elm string. The following diagram explains the type signature of decodeString in detail. When decoding fails, decodeString returns a value of type Error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With