gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:07:39 24 4
gpt4 key购买 nike

给定对象的 JSON 列表,例如:

[{"id":"1", "name":"Jane"},{"id":"2", "name":"Joe"}]

我如何将其解码为 Dict String Fooid作为键和在哪里 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 - Elm - 如何将对象的 json 列表解码为 Dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59248616/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com