我正在嘗試處理這個庫中的一些錯誤描述,因為我需要它們是嵌套的 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 回答

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
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 關注
- 139 瀏覽
添加回答
舉報
0/150
提交
取消