dongmu2517 2018-08-22 04:59
浏览 159
已采纳

拆分后如何将数组转换为嵌套的json对象

I'm trying to deal with some error descriptions from this library because I need them to be nested JSON objects.

The errors seem to be an array originally, like this:

["String length must be greater than or equal to 3","Does not match format 'email'"]

I needed that to also include the field name of the containing error:

["Field1: String length must be greater than or equal to 3","Email1: Does not match format 'email'"]

After that I need to split each array value by colon : so I can have the field name and error description in separate variables like slice[0] and slice[1].

With that I want to make a nested JSON object like so:

{
    "errors": {
        "Field1": "String length must be greater than or equal to 3",
        "Email1": "Does not match format 'email'"
    }
}

This is my way of trying to achieve this:

var errors []string
for _, err := range result.Errors() {
    // Append the errors into an array that we can use to split later
    errors = append(errors, err.Field() + ":" + err.Description())
}

// Make the JSON map we want to append values to
resultMap := map[string]interface{}{
    "errors": map[string]string {
        "Field1": "",
        "Email1": ""
    },
}

// So we actually can use the index keys when appending
resultMapErrors, _ := resultMap["errors"].(map[string]string)

for _, split := range errors {
    slice := strings.Split(split, ":")
    for _, appendToMap := range resultMapErrors {
        appendToMap[slice[0]] = slice[1] // append it like so?
    }
}

finalErrors, _ := json.Marshal(resultMapErrors)
fmt.Println(string(finalErrors))

But this throws the errors

main.go:59:28: non-integer string index slice[0]
main.go:59:39: cannot assign to appendToMap[slice[0]]

Any clue how I can achieve this?

展开全部

  • 写回答

1条回答 默认 最新

  • douqi3064 2018-08-22 05:16
    关注
    var errors = make(map[string]string)
    for _, err := range result.Errors() {
        errors[err.Field()] = err.Description()
    }
    
    // Make the JSON map we want to append values to
    resultMap := map[string]interface{}{
        "errors": errors,
    }
    
    finalErrors, _ := json.Marshal(resultMap)
    fmt.Println(string(finalErrors))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部