我的问题是我希望能够遍历每个服务器并在该循环中遍历 UsageData我当前的循环给了我一个关于遍历资产的错误,不知道为什么我无法访问 assets.Server.UsageData这是我的代码:https ://go.dev/play/p/ttNVW5_Q4Yspackage mainimport ( "encoding/json" "fmt")type Asset struct { Server struct { Host string `json:"host"` Port string `json:"port"` } `json:"server"` Postgres struct { Host string `json:"host"` User string `json:"user"` Password string `json:"password"` DB string `json:"db"` UsageData []struct { Region string `json:"Region"` Mbps int `json:"Mpbs"` } `json:"UsageData"` } `json:"database"`}func main() { jsonConfig := []byte(`[ { "server":{ "host":"serverA", "port":"8080"}, "database":{ "host":"serverA", "user":"db_user", "password":"supersecret", "db":"A_db", "UsageData":[{"Region":"US","Mbps":100}, {"Region":"EU","Mbps":140}] } }, { "server":{ "host":"serverB", "port":"8383"}, "database":{ "host":"serverB", "user":"db_user2", "password":"acbd123", "db":"B_db", "UsageData":[{"Region":"US","Mbps":58}, {"Region":"EU","Mbps":250}] } }]`) var assets []Asset err := json.Unmarshal(jsonConfig, &assets) if err != nil { panic(err) } fmt.Printf("Assets: %+v\n", assets) //fmt.Printf("Config: %+v\n", assets.Server.Host) //fmt.Printf("Config: %+v\n", assets.database.UsageData) //fmt.Printf("Config: %+v\n", assets.Server.UsageData) for _, asset := range assets { fmt.Printf("%v\n", asset) //for _, Usage := range assets.UsageData { // fmt.Printf("%v\n",Usage) //} }}** 正确答案的代码,我错误地调用了嵌套结构**https://go.dev/play/p/tEbA405WWbC
- 1 回答
- 0 关注
- 94 浏览
添加回答
举报
0/150
提交
取消