Json.Decode.Pipeline 在列表中 (elm 0.18)
Json.Decode.Pipeline on a list (elm 0.18)
我有一个带有嵌套列表的类型别名,我想用 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?
这是如何工作的?
您需要将解码器传递给 Decode.list
。在您的情况下,它将是根据您的 Student
类型的形状定制的。
这还没有经过测试,但是像下面这样的东西应该工作:
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)
请参阅 this post 编写自定义标志解码器,这应该具有指导意义。
我有一个带有嵌套列表的类型别名,我想用 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?
这是如何工作的?
您需要将解码器传递给 Decode.list
。在您的情况下,它将是根据您的 Student
类型的形状定制的。
这还没有经过测试,但是像下面这样的东西应该工作:
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)
请参阅 this post 编写自定义标志解码器,这应该具有指导意义。