Elm-如何将对象的json列表解码为Dict

问题描述 投票:2回答:1

给出对象的JSON列表,例如:

[{"id":"1", "name":"Jane"},{"id":"2", "name":"Joe"}]

如何使用Dict String Foo作为键并将其解码为id,并且其中Foo是类型为{id: String, name: String}的记录? (请注意,记录中还包含ID。)

json elm
1个回答
2
投票

例如,使用以下组合:


import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)

type alias Foo =
    { id : String, name : String }

fooDecoder : Decoder Foo
fooDecoder =
    Decode.map2 Foo (Decode.field "id" Decode.string) (Decode.field "name" Decode.string)

theDecoder : Decoder (Dict String Foo)
theDecoder =
    Decode.list (Decode.map2 Tuple.pair (Decode.field "id" Decode.string) fooDecoder)
        |> Decode.map Dict.fromList

© www.soinside.com 2019 - 2024. All rights reserved.