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。)
例如使用以下组合:
Json.Decode.list
(https://package.elm-lang.org/packages/elm/json/latest/Json-Decode#list
Json.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
给定 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