gpt4 book ai didi

json - 我如何 Json.decode 联合类型?

转载 作者:行者123 更新时间:2023-12-03 15:25:15 27 4
gpt4 key购买 nike

我在 module Foo exposing (..) 中有一个像这样定义的类型:

type Foo
= Bar
{ a : String
, b : String
}
| Baz
...

然后我尝试创建一个 Json Decoder在一个单独的模块中解码该类型,如下所示:
barDecoder : Decoder Bar
barDecoder =
map2 Bar
(field "a" string)
(field "b" string)

Elm 编译器在 map2 Bar 上给我一个错误。表示该类型 Bar 的行没有找到。包含解码器的模块有 import Foo exposing (..) .我还尝试将此函数移动到包含类型定义的同一模块中并得到相同的错误,因此它与位于单独的模块中没有任何关系。

我试过把它改成 map2 Foo.Bar ,但这也不起作用。

像这样解码联合类型的正确方法是什么?

最佳答案

您应该使用 Json.Decode.oneOf如果你有多种解码 json 的方法。

这是如何使用它的示例。
(我编造了Baz,因为你没有指定它。)

import Json.Decode as Json

type Foo
= Bar
{ a : String
, b : String
}
| Baz Int


barDecoder : Json.Decoder Foo
barDecoder =
Json.map2 (\x y -> Bar { a = x, b = y })
(Json.field "a" Json.string)
(Json.field "b" Json.string)


bazDecoder : Json.Decoder Foo
bazDecoder =
Json.map Baz Json.int


fooDecoder : Json.Decoder Foo
fooDecoder =
Json.oneOf [ barDecoder, bazDecoder ]

关于json - 我如何 Json.decode 联合类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41969381/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com