我的JSON如下所示
{ "resp":
[ [1, "things"]
, [2, "more things"]
, [3, "even more things"]
]
}
问题是我无法将JSON元组解析为Elm元组:
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)
?
您需要一个将大小为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
(请注意,如果有两个以上的元素,我的示例解码器不会失败,但是应该使您指向正确的方向)
import Json.Decode as Decode
decodeTuple =
Decode.map2 Tuple.pair
(Decode.index 0 Decode.int)
(Decode.index 1 Decode.string)
然后,请注意,列表
Decode.list decodeTuple
我无法使用Chad Gilbert或Simon H的解决方案来与Elm 0.19一起工作。我对Elm来说还很陌生,但这就是我可以工作的地方:
import Json.Decode as Decode
import Json.Decode.Extra as Decode
{-| Decodes two fields into a tuple.
-}
decodeAsTuple2 : String -> Decode.Decoder a -> String -> Decode.Decoder b -> Decode.Decoder (a, b)
decodeAsTuple2 fieldA decoderA fieldB decoderB =
let
result : a -> b -> (a, b)
result valueA valueB =
(valueA, valueB)
in
Decode.succeed result
|> Decode.andMap (Decode.field fieldA decoderA)
|> Decode.andMap (Decode.field fieldB decoderB)