【问题标题】:Elm: Decode a JSON array with a single element into a stringElm:将具有单个元素的 JSON 数组解码为字符串
【发布时间】:2018-07-02 04:48:17
【问题描述】:

寻找类似的东西,但找不到确切的问题。

我有一个从服务器端验证返回的 JSON,如下所示:

{ 
  "field": ["field-name"], 
  "messages":["message","message"]
}

我想做的是把它解码成一个榆树记录

{ field: String, messages: List String }

但是,我在使用 err, field 字段时遇到了问题。我无法将单个元素 JSON 数组转换为该元素的字符串。

是否甚至可以使用解码,或者我最好将其解码成一个列表,然后从列表中抓取头部。

这是我用来解码的:

valErrorDecoder : Decode.Decoder ValError
valErrorDecoder =
decode ValError
    |> required "field" (Decode.list Decode.string)
    |> required "messages" (Decode.list Decode.string)

感谢您的帮助!

【问题讨论】:

  • 我遇到了同样的问题。尝试了两种解决方案。但是,如果 Json 中出现空列表,则需要“Maybe”。 Decode.index 不会捕获失败。

标签: json frontend elm decoder


【解决方案1】:

试试Decode.index,应该可以解决问题。

valErrorDecoder : Decode.Decoder ValError
valErrorDecoder =
decode ValError
    |> required "field" (Decode.index 0 Decode.string)
    |> required "messages" (Decode.list Decode.string)

【讨论】:

  • 谢谢!一位同事建议使用 Decode.map,但这看起来有点简单。
【解决方案2】:

您在评论中提到一位同事建议Decode.map。如果您好奇,下面是该(更复杂的)解决方案的样子:

firstElementDecoder : Decode.Decoder a -> Decode.Decoder a
firstElementDecoder baseDecoder = Decode.list baseDecoder
 |> Decode.map List.head
 |> Decode.andThen (Maybe.map Decode.succeed >> Maybe.withDefault (Decode.fail "Empty list"))

这里发生了什么?我们首先解码一个字符串列表,然后将List.head 函数映射到该列表,得到Decoder (Maybe String)。函数

Maybe.map Decode.succeed 
  >> Maybe.withDefault (Decode.fail "Empty list")

接受Maybe 并将其转换为解码器,该解码器要么成功(使用maybe 的值),要么失败(使用“空列表”错误消息)。我们使用这个函数作为Decode.andThen 的参数,其中:

  1. 将列表解码器中的Maybe 传递给上面的函数,得到Decode.succeedDecode.fail
  2. 运行返回的解码器,使用适当的值成功或失败。

所以,是的,Decode.index 0 更简单!但是看到更长的解决方案也可能很有趣:-)

【讨论】:

  • 感谢您添加这个额外的答案。它最终使我能够构建一个仅在输入是单个字符串时才成功的解码器字符。它还展示了如何将任意额外验证插入到解码器链中。
猜你喜欢
  • 1970-01-01
  • 2012-07-07
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 2012-06-18
  • 2010-09-09
  • 1970-01-01
相关资源
最近更新 更多