Elm - 如何将 json 对象列表解码为字典

Elm - How to decode a json list of objects into a Dict

给定 JSON 个对象列表,例如:

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

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

例如使用以下组合:


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