将JSON元组解码为Elm元组 [英] Decode a JSON tuple to Elm tuple

查看:151
本文介绍了将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)

这篇关于将JSON元组解码为Elm元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆