Elm:将具有单个元素的JSON数组解码为字符串 [英] Elm: Decode a JSON array with a single element into a string
问题描述
看起来像这样,但是找不到确切的问题。
had a look for something like this, but can't find the exact issue.
我从服务器端验证返回了一个JSON,如下所示:
I have a JSON back from server side validation that looks like:
{
"field": ["field-name"],
"messages":["message","message"]
}
我想做的就是将其解码为像这样的榆树记录
What I would like to do is decode it into an elm record like
{ field: String, messages: List String }
但是,我遇到了错误的字段字段。我在将单个元素的JSON数组转换为该元素的字符串时遇到麻烦。
However, I'm having trouble with the err, field field. I'm having trouble turning a single element JSON array into just a string of that element.
使用Decode甚至可能,还是最好将其解码为列出,然后从列表中抢先。
Is it even possible with Decode, or am I better of Decoding it into a List and then just grabbing the head from the list.
这就是我要解码的内容:
This is what I have for the decode:
valErrorDecoder : Decode.Decoder ValError
valErrorDecoder =
decode ValError
|> required "field" (Decode.list Decode.string)
|> required "messages" (Decode.list Decode.string)
感谢您的帮助!
推荐答案
尝试 Decode.index
,应该可以解决问题。
Try Decode.index
, that should do the trick.
valErrorDecoder : Decode.Decoder ValError
valErrorDecoder =
decode ValError
|> required "field" (Decode.index 0 Decode.string)
|> required "messages" (Decode.list Decode.string)
这篇关于Elm:将具有单个元素的JSON数组解码为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!