Given a JSON list of objects e.g.:
[{"id":"1", "name":"Jane"},{"id":"2", "name":"Joe"}]
How do I decode this into a Dict String Foo
with the id
as keys and where Foo
is a record of type {id: String, name: String}
? (Note that the record also contains the id.)
Use for example a combination of:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With