Elm 解码JSON,其中值可以是字符串或不同值的数组

Elm 解码JSON,其中值可以是字符串或不同值的数组,elm,Elm,还有一个关于如何用Elm解码的问题 所以问题是我需要解码一个值,它可以是一个字符串,例如 “价格未知” 也可以是2个元素的数组,其中第一个是字符串,第二个是浮点: [“价格”,50.5] 对于最终值,我有一个类型: type Something = PriceUnknown = Price Float 我需要将json响应中的值转换为 我试着使用一些东西,在字里行间: decode MyString |> required "other_value" Json.Decode.

还有一个关于如何用Elm解码的问题

所以问题是我需要解码一个值,它可以是一个字符串,例如

“价格未知”

也可以是2个元素的数组,其中第一个是字符串,第二个是浮点:

[“价格”,50.5]

对于最终值,我有一个类型:

type Something
  = PriceUnknown
  = Price Float
我需要将json响应中的值转换为

我试着使用一些东西,在字里行间:

decode MyString
  |> required "other_value" Json.Decode.string
  |> required "price" JD.oneOf [JD.string, JD.list (JD.oneOf [JD.string, JD.float])] |> JD.map mapper
(我在这里使用的是
json\u decode\u管道
package)

但很明显,它抱怨列表中的不同值等等,所以我被卡住了


提前谢谢。

您非常接近,但是
中的所有
解码器都必须具有相同的类型。此外,分解混合列表可能是一件痛苦的事情。这用于简化手动解码步骤

myDecoder : Decoder SomethingElse
myDecoder =
    decode MyString
        |> required "other_value" Json.Decode.string
        |> required "price" priceDecoder


priceDecoder : Decoder Something
priceDecoder =
    JD.oneOf
        [ priceUnknownDecoder
        , priceKnownDecoder
        ]


priceUnknownDecoder : Decoder Something
priceUnknownDecoder =
    JD.string
        |> JD.andThen
            (\string ->
                if string == "price_unknown" then
                    JD.succeed PriceUnknown
                else
                    JD.fail "Invalid unknown price string."
            )


priceKnownDecoder : Decoder Something
priceKnownDecoder =
    listTupleDecoder
        JD.string
        JD.float
        |> JD.andThen
            (\(tag, price) ->
                if tag == "price" then
                    JD.succeed (Price price)
                else
                    JD.fail "Invalid tag string."
            )


listTupleDecoder : Decoder a -> Decoder b -> Decoder (a, b)
listTupleDecoder firstD secondD =
    JD.list JD.value
        |> JD.andThen
            (\values ->
                case values of
                    [first, second] ->
                        Result.map2
                            (,)
                            JD.decodeValue firstD first
                            JD.decodeValue secondD second
                            |> JD.Extra.fromResult

                    _ ->
                        JD.fail "There aren't two values in the list."
            )

我有一种感觉,那不会是一句台词……:)谢谢