2017-09-17 54 views
1

我有一個嵌套列表的類型別名,我想用Json.Decode.Pipeline解析。列表上的Json.Decode.Pipeline(elm 0.18)

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? 

這是如何工作的?

回答

1

您需要將解碼器傳遞給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職位上編寫自定義標記的解碼器應該是有益的。