我的 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




