亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

拆分后如何將數組轉換為嵌套的json對象

拆分后如何將數組轉換為嵌套的json對象

Go
慕虎7371278 2023-03-21 17:14:48
我正在嘗試處理這個庫中的一些錯誤描述,因為我需要它們是嵌套的 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))


查看完整回答
反對 回復 2023-03-21
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號