Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

elm

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.)

like image 593
stoft Avatar asked Dec 09 '19 12:12

stoft


1 Answers

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

like image 171
stoft Avatar answered Oct 23 '22 05:10

stoft