See Ellie for a working example. This example uses the NoRedInk/elm-decode-pipeline module.
Given a list of JSON objects, which themselves contain lists of JSON objects:
[
{
"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 }
]
}
]
If the above string is in the payload
string, that can be decoded using the following:
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