给出对象的JSON列表,例如:
[{"id":"1", "name":"Jane"},{"id":"2", "name":"Joe"}]
如何使用Dict String Foo
作为键并将其解码为id
,并且其中Foo
是类型为{id: String, name: String}
的记录? (请注意,记录中还包含ID。)
例如,使用以下组合:
Json.Decode.list
(https://package.elm-lang.org/packages/elm/json/latest/Json-Decode#listJson.Decode.map2
(https://package.elm-lang.org/packages/elm/json/latest/Json-Decode#map2)Dict.fromList
(https://package.elm-lang.org/packages/elm/core/latest/Dict#fromList)Tuple.pair
(https://package.elm-lang.org/packages/elm/core/latest/Tuple#pair)
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