将JSON元组解码为Elm元组

编程入门 行业动态 更新时间:2024-10-25 06:29:12
本文介绍了将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元组

本文发布于:2023-08-03 08:09:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1285498.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JSON   Elm

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!