2017-03-09 75 views
3

我的JSON如下所示解码JSON元组榆树元组

{ "resp": 
    [ [1, "things"] 
    , [2, "more things"] 
    , [3, "even more things"] 
    ] 
} 

的问题是,我无法分析JSON元组到榆树的元组:

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)

+1

您的JSON不符合您的描述 - '[1, “物联网”]'是一个JSON *阵列*,而不是一个JSON对象* * (我期望自从你提到JSON元组以来)。尝试使用“{1”,“}”,或者更改您的Elm解码器以接受列表列表。 –

回答

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))) 

然后,您可以修改原来的例子如下:

decodeThings : Decoder (List (Int, String)) 
decodeThings = field "resp" <| list <| arrayAsTuple2 int string 

(请注意,如果有两个以上的元素,我的例子解码器并没有失败,但它应该让你在正确的方向)

+0

工作就像一个魅力。为什么没有元组的默认实现,当它们被表示为列表? – Patrick

+2

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

3

简单的是

map2 (,) (index 0 string) (index 1 string) 

,然后,当你注意,该列表

list <| map2 (,) (index 0 string) (index 1 string)