Decode a JSON tuple to Elm tuple

柔情痞子 提交于 2019-12-05 08:28:26
Chad Gilbert

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)

import Json.Decode exposing (map2, index, string, list)

Simplest is

map2 Tuple.pair (index 0 string) (index 1 string)

and then, as you note, for the list

list <| map2 Tuple.pair (index 0 string) (index 1 string)

I could not get either Chad Gilbert's or Simon H's solution to work with Elm 0.19. I am quite new to Elm, but this is what I could get to work:

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!