我的问题是
我希望能够遍历每个服务器并在该循环中遍历 UsageData
我当前的循环给了我一个关于遍历资产的错误,不知道为什么
我无法访问 assets.Server.UsageData
这是我的代码:https ://go.dev/play/p/ttNVW5_Q4Ys
package main
import (
"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
郎朗坤
相关分类