我需要從 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
從 GO 中的 json 數組映射輸出
慕碼人8056858
2022-07-11 15:41:12