2017-03-09 81 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)