将JSON元组解码为Elm元组
我的JSON如下所示
{ "resp":
[ [1, "things"]
, [2, "more things"]
, [3, "even more things"]
]
}
问题是我无法将JSON元组解析为Elm元组:
the problem is that I can't parse the JSON tuples into Elm tuples:
decodeThings : Decoder (List (Int, String))
decodeThings = field "resp" <| list <| map2 (,) int string
它可以编译,但是运行时会抛出
It compiles, but when ran, it throws
BadPayload "Expecting an Int at _.resp[2] but instead got [3, \"even more things\"]
由于某种原因,它只读取[3, "even more things"]
而不是JSON格式的元组.
如何将JSON解析为List (Int, String)
?
For some reason it reads [3, "even more things"]
as only one thing and not as tuple in JSON format.
How can I parse my JSON into a List (Int, String)
?
您需要一个解码器,该解码器将大小为2的javascript数组转换为大小为2的Elm元组.这是一个示例解码器:
You need a decoder which turns a javascript array of size two into an Elm tuple of size two. Here is an example decoder:
arrayAsTuple2 : Decoder a -> Decoder b -> Decoder (a, b)
arrayAsTuple2 a b =
index 0 a
|> andThen (\aVal -> index 1 b
|> andThen (\bVal -> Json.Decode.succeed (aVal, bVal)))
然后您可以修改原始示例,如下所示:
You can then amend your original example as follows:
decodeThings : Decoder (List (Int, String))
decodeThings = field "resp" <| list <| arrayAsTuple2 int string
(请注意,如果有两个以上的元素,我的示例解码器不会失败,但是应该使您指向正确的方向)
(Note that my example decoder does not fail if there are more than two elements, but it should get you pointed in the right direction)