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

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

從 GO 中的 json 數組映射輸出

從 GO 中的 json 數組映射輸出

Go
慕碼人8056858 2022-07-11 15:41:12
我需要從 Json 數組創建一個地圖,我從下面的 GO 開始,有點卡住,有什么指針嗎?    package mainimport (    "encoding/json"    "fmt"    "strconv")func main() {    jsonStr := `{  "employee": [    {      "id": 14325,      "grpname": "senior"    },    {      "id": 234,      "grpname": "junior"    }  ]}`    type Group struct {        Employee []struct {            GroupName string            GroupId   int        }    }    var group []Group    var groupMap []map[string]interface{}    err := json.Unmarshal([]byte(jsonStr), &groupMap)    if err != nil {        panic(err)    }    for _, groupData := range groupMap {        // convert map to array of Group struct        var g Group        g.GroupName = fmt.Sprintf("%s", groupData["grpname"])        g.GroupId, _ = strconv.Atoi(fmt.Sprintf("%v", groupData["id"]))        group = append(group, g)    }    fmt.Println(group)}錯誤:./prog.go:45:4: g.GroupName undefined (type Group has no field or method GroupName)./prog.go:46:4: g.GroupId undefined (type Group has no field or method GroupId)預期輸出:{"senior": 14325,"junior": 234}嘗試了一些類似下面的操作,但出現錯誤:出現錯誤:%!(EXTRA string=json: cannot unmarshal array into Go struct field GetEmpResponse.employee of type map[string][]model.Employee)類型 GetEmpResponse 結構 { Employee map[string][]Employee json:"employee" }為我的測試嘗試簡化Json,請參考 play.golang.org
查看完整描述

1 回答

?
嗶嗶one

TA貢獻1854條經驗 獲得超8個贊

empResponse.Employee是一個數組,所以你必須通過索引訪問它的元素,例如

empResponse.Employee[0].ID


查看完整回答
反對 回復 2022-07-11
  • 1 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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