问题描述
寻找类似的东西,但找不到确切的问题.
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 }
但是,我在使用 err, field 字段时遇到了问题.我无法将单个元素 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.
是否甚至可以使用解码,或者我最好将其解码成一个列表,然后从列表中抓取头部.
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.
这是我用来解码的:
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 数组解码为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!