我正在尝试处理这个库中的一些错误描述,因为我需要它们是嵌套的 JSON 对象。错误似乎最初是一个数组,如下所示:["String length must be greater than or equal to 3","Does not match format 'email'"]我需要它还包括包含错误的字段名称:["Field1: String length must be greater than or equal to 3","Email1: Does not match format 'email'"]之后,我需要用冒号分隔每个数组值,这样我就可以在单独的变量(如和 ):中包含字段名称和错误描述。slice[0]slice[1]有了它,我想像这样制作一个嵌套的 JSON 对象:{ "errors": { "Field1": "String length must be greater than or equal to 3", "Email1": "Does not match format 'email'" }}这是我尝试实现这一目标的方式:var errors []stringfor _, 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 toresultMap := map[string]interface{}{ "errors": map[string]string { "Field1": "", "Email1": "" },}// So we actually can use the index keys when appendingresultMapErrors, _ := 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))但这会引发错误main.go:59:28: non-integer string index slice[0]main.go:59:39: cannot assign to appendToMap[slice[0]]任何线索我怎么能做到这一点?
1 回答
![?](http://img1.sycdn.imooc.com/5923e28b0001bb7201000100-100-100.jpg)
qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
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))
- 1 回答
- 0 关注
- 117 浏览
添加回答
举报
0/150
提交
取消