gpt4 book ai didi

json - 将 JSON 元组解码为 Elm 元组

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

我的 JSON 如下所示

{ "resp":
[ [1, "things"]
, [2, "more things"]
, [3, "even more things"]
]
}

问题是我无法将 JSON 元组解析为 Elm 元组:
decodeThings : Decoder (List (Int, String))
decodeThings = field "resp" <| list <| map2 (,) int string

它编译,但是当运行时,它抛出

BadPayload "Expecting an Int at _.resp[2] but instead got [3, \"even more things\"]

出于某种原因,它显示为 [3, "even more things"]只是一件事,而不是 JSON 格式的元组。
如何将我的 JSON 解析为 List (Int, String) ?

最佳答案

公认的答案比它需要的更复杂。尝试:

import Json.Decode as Decode

decodeTuple : Decode.Decoder (Int, String)
decodeTuple =
Decode.map2 Tuple.pair
(Decode.index 0 Decode.int)
(Decode.index 1 Decode.string)
然后,正如您所指出的,对于列表
Decode.list decodeTuple

关于json - 将 JSON 元组解码为 Elm 元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42703764/

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