【问题标题】:Elm: JSON decoder, convert String to BoolElm:JSON 解码器,将 String 转换为 Bool
【发布时间】:2016-05-11 09:07:42
【问题描述】:

我收到一个如下所示的 JSON:

{ name: "NAME1", value: "true" }

我想创建一个 json 解码器来创建这样的记录:

{ name: "NAME1", value: True }

我正在尝试制作一个将“真”转换为真的解码器。到目前为止我是这样做的:

userProperties : Json.Decode.Decoder Props
userProperties =
  Json.Decode.object2 (,)
    ("name" := Json.Decode.string)
    ("value" := Json.Decode.string)
      `andThen` \val ->
        let
          newVal = -- Do something here?
        in
          Json.Decode.succeed <| newVal

【问题讨论】:

  • 你有val,在你的例子中应该是"true",所以写给newVal的赋值应该是相当简单的,这取决于你想要什么语义——可能只是一个@ 987654327@ 表达式。你在解决这个问题时遇到了什么问题?

标签: elm


【解决方案1】:

您的示例中存在一些问题,所以让我们逐一分析。

您还没有显示Props 的定义,所以根据您的示例,我假设它是这样的:

type alias Props = { name : String, value : Bool }

您将(,) 作为第一个参数传递给object2,这表明您将返回一个元组类型的解码器。那应该是:

Json.Decode.object2 Props

现在,您使用 andThen 的方式将无法编译,因为它的优先顺序。如果你把整个事情用括号括起来,它看起来像这样:

userProperties =
  (Json.Decode.object2 Props
    ("name" := Json.Decode.string)
    ("value" := Json.Decode.string))
      `andThen` \val ->
        let
          newVal = -- Do something here?
        in
          Json.Decode.succeed <| newVal

这不会是正确的,因为您想要andThen"value" 字段中的字符串"true"。为此,我建议创建一个提供该布尔解码器的解码器:

stringBoolDecoder : Json.Decode.Decoder Bool
stringBoolDecoder =
  string `andThen` \val ->
    case val of
      "true" -> succeed True
      "false" -> succeed False
      _ -> fail <| "Expecting \"true\" or \"false\" but found " ++ val

我只是猜测"false" 的处理方式和包罗万象的下划线。根据您的业务案例更改其实施。

在构建复杂的解码器时,通常最好将解码器定义分解成尽可能小的块,就像上面一样。

最后,我们现在可以重新定义您的 userProperties 解码器,以便在适当的位置使用 stringBoolDecoder

userProperties : Json.Decode.Decoder Props
userProperties =
  Json.Decode.object2 Props
    ("name" := Json.Decode.string)
    ("value" := stringBoolDecoder)

【讨论】:

  • 很好的答案!我正在慢慢将这些点与 FP 方法联系起来。
猜你喜欢
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 2022-10-12
  • 1970-01-01
  • 2019-03-21
  • 2017-10-20
  • 2019-10-21
  • 1970-01-01
相关资源
最近更新 更多