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

sto*_*oft 6 json elm

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

[{"id":"1", "name":"Jane"},{"id":"2", "name":"Joe"}]
Run Code Online (Sandbox Code Playgroud)

如何Dict String Foo使用idas 键将其解码为 a以及Footype 的记录在{id: String, name: String}哪里?(请注意,该记录还包含 id。)

sto*_*oft 5

例如使用以下组合:


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

Run Code Online (Sandbox Code Playgroud)