将JSON元组解码为Elm元组

ptk*_*ato 5 json elm

我的JSON如下所示

{ "resp":
    [ [1, "things"]
    , [2, "more things"]
    , [3, "even more things"]
    ]
}
Run Code Online (Sandbox Code Playgroud)

问题是我无法将JSON元组解析为Elm元组:

decodeThings : Decoder (List (Int, String))
decodeThings = field "resp" <| list <| map2 (,) int string
Run Code Online (Sandbox Code Playgroud)

它编译,但运行时,它会抛出

BadPayload "Expecting an Int at _.resp[2] but instead got [3, \"even more things\"]
Run Code Online (Sandbox Code Playgroud)

由于某种原因,它只读取[3, "even more things"]一件事而不是JSON格式的元组.
我怎样才能将我的JSON解析成List (Int, String)

Sim*_*n H 10

import Json.Decode as Decode

decodeTuple = 
    Decode.map2 Tuple.pair 
        (Decode.index 0 Decode.int) 
        (Decode.index 1 Decode.string)
Run Code Online (Sandbox Code Playgroud)

最简单的是

Decode.list decodeTuple
Run Code Online (Sandbox Code Playgroud)

然后,正如您所说,列表

import Json.Decode as Decode

decodeTuple = 
    Decode.map2 Tuple.pair 
        (Decode.index 0 Decode.int) 
        (Decode.index 1 Decode.string)
Run Code Online (Sandbox Code Playgroud)


Cha*_*ert 8

你需要一个解码器,将大小为2的javascript数组转换为大小为2的Elm元组.这是一个示例解码器:

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)))
Run Code Online (Sandbox Code Playgroud)

然后,您可以修改原始示例,如下所示:

decodeThings : Decoder (List (Int, String))
decodeThings = field "resp" <| list <| arrayAsTuple2 int string
Run Code Online (Sandbox Code Playgroud)

(注意,如果有两个以上的元素,我的示例解码器不会失败,但它应该让你指向正确的方向)

  • 曾经有在原生javascript中实现的`tupleN`解码器,但那些[删除](https://github.com/elm-lang/core/commit/3b999526e08ac517c0223a55c78cb13e752be3f8),推荐的处理方法是使用[index] (https://github.com/elm-lang/core/commit/c341774223da6ad30eb67d1628cbea68c6fcd27e).我不确定究竟是什么原因. (2认同)