elm:解码包含json数组的json [英] elm: decode json that contains a json array

查看:102
本文介绍了elm:解码包含json数组的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要解码在elm中包含json arrayjson.这是我的模型:

So I need to decode a json that contains a json array in elm. Here is my model:

type alias ValidationResult =
    { parameter : String
    , errorMessage : String
    }


type alias ErrorResponse =
    { validationErrors : List ValidationResult }

这是json的示例:

{"ValidationErrors": [{"Parameter": "param1","ErrorMessage": "message 1"},{"Parameter": "param2","ErrorMessage": "error message 2"}]}

我试图创建一个ValidationResult解码器,例如:

I've tried to create a ValidationResult decoder, like:

decodeValidationResults : Decoder ValidationResult
decodeValidationResults =
  map2 ValidationResult
    (at [ "Parameter" ] Json.Decode.string)
    (at [ "ErrorMessage" ] Json.Decode.string)

但是我不知道该怎么做.

But I don't know how to proceed further.

我正在使用elm 0.18

I am using elm 0.18

推荐答案

您快到了!您只需要一个解码器即可解码ErrorResponse类型.为此,请创建另一个解码器,该解码器使用您已经创建的解码器列表,并假设字段名称为"ValidationErrors":

You are almost there! You just need a decoder that decodes the ErrorResponse type. To do so, create another decoder that uses a list of the decoder you've already created, assuming the field name is "ValidationErrors":

import Json.Decode exposing (..)

decodeErrorResponse : Decoder ErrorResponse
decodeErrorResponse =
    map ErrorResponse
        (field "ValidationErrors" (list decodeValidationResults))

一点建议:只有一个级别时,可以使用Json.Decode.field代替Json.Decode.at.您可以这样重写decodeValidationResults:

One bit of advice: You can use Json.Decode.field instead of Json.Decode.at when there is only a single level. You can rewrite decodeValidationResults as this:

decodeValidationResults : Decoder ValidationResult
decodeValidationResults =
  map2 ValidationResult
    (field "Parameter" string)
    (field "ErrorMessage" string)

这篇关于elm:解码包含json数组的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆