gpt4 book ai didi

elm - 是否可以使用 elm-decode-pipeline 有条件地解码某些字段

转载 作者:行者123 更新时间:2023-12-02 17:33:38 27 4
gpt4 key购买 nike

我想解码一个 API 响应,其中一个字段值(类别)将确定如何使用不同的子解码器解码另一个字段(配置) .

我能够使用 Json.Decode.mapn 函数和 andThen 函数完成这样的事情,但我想知道是否有任何方法可以使用elm-decode-pipeline 因为它有更好的 API,我最终会用完 mapn 函数。

一个最小且有些微不足道的例子如下:

type alias Machine =
{ name : String
, specs : MachineSpecs
}

type MachineSpecs
= ElectricMachine ElectricSpecs
| MechanicalMachine MechanicalSpecs
| UnknownMachine

type alias ElectricSpecs =
{ voltage : Int
}

type alias MechanicalSpecs =
{ gears : Int
}

一些有效的 JSON 响应将具有以下形状:

{
"name": "Foo electric machine",
"category": "electric",
"configuration": {
"voltage": 12
}
}
{
"name": "Bar mechanical machine",
"category": "mechanical",
"configuration": {
"gears": 5
}
}
{
"name": "Some machine of unknown category",
"category": "foo"
}

我尝试了一种与使用 mapn 函数类似的方法,但它不起作用。

decoder : Decoder Machine
decoder =
decode Machine
|> required "name" string
|> required "category" (string |> andThen catDec)


catDec : String -> Decoder MachineSpecs
catDec cat =
case cat of
"electric" ->
map ElectricMachine electricDecoder

"mechanical" ->
map MechanicalMachine mechanicalDecoder

_ ->
succeed UnknownMachine


electricDecoder : Decoder ElectricSpecs
electricDecoder =
decode ElectricSpecs
|> requiredAt [ "configuration", "voltage" ] int


mechanicalDecoder : Decoder MechanicalSpecs
mechanicalDecoder =
decode MechanicalSpecs
|> requiredAt [ "configuration", "gears" ] int

事实上,我还没有在网络或文档上看到任何同时使用 Json.Decode.PipelineandThen 的示例,所以我不确定是否可能。

我已经为此问题设置了一个在线示例,显示它如何无法解码条件部分:https://runelm.io/c/3ut

最佳答案

作为替代方案,您可以将 andThen 绑定(bind)放置在管道 ( ellie example ) 之前:

decoder : Decoder Machine
decoder =
field "category" string
|> andThen catDec
|> andThen
(\cat ->
decode Machine
|> required "name" string
|> hardcoded cat
)

如果您的 mapN 号码用完,请考虑切换到 andMap (或中缀版本 |: )在 elm-community/json-extra 中包。

关于elm - 是否可以使用 elm-decode-pipeline 有条件地解码某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41465430/

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