解码包含对象列表的对象列表
*请参阅 Ellie 的工作示例。*此示例使用 NoRedInk / elm-decode-pipeline 模块。
给定一个 JSON 对象列表,它们本身包含 JSON 对象列表:
[
{
"id": 0,
"name": "Item 1",
"transactions": [
{ "id": 0, "amount": 75.00 },
{ "id": 1, "amount": 25.00 }
]
},
{
"id": 1,
"name": "Item 2",
"transactions": [
{ "id": 0, "amount": 50.00 },
{ "id": 1, "amount": 15.00 }
]
}
]
如果上面的字符串在 payload
字符串中,则可以使用以下代码解码:
module Main exposing (main)
import Html exposing (..)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline as JP
import String
type alias Item =
{ id : Int
, name : String
, transactions : List Transaction
}
type alias Transaction =
{ id : Int
, amount : Float
}
main =
Decode.decodeString (Decode.list itemDecoder) payload
|> toString
|> String.append "JSON "
|> text
itemDecoder : Decoder Item
itemDecoder =
JP.decode Item
|> JP.required "id" Decode.int
|> JP.required "name" Decode.string
|> JP.required "transactions" (Decode.list transactionDecoder)
transactionDecoder : Decoder Transaction
transactionDecoder =
JP.decode Transaction
|> JP.required "id" Decode.int
|> JP.required "amount" Decode.float