我正试图处理来自
this library
因为我需要它们是嵌套的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 []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))
但这会造成错误
main.go:59:28: non-integer string index slice[0]
main.go:59:39: cannot assign to appendToMap[slice[0]]