英文:
How to range over nested struct in golang?
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对Golang还不熟悉:
这是我定义的结构体:
type Name map[string]Info
type Info struct {
Addresses string `json:"addresses"`
Host map[string]Server `json:"host"`
}
type Server struct {
Ipaddress string `json:"ip"`
Status string `json:"status"`
}
var result Name
在解析JSON后,我得到了:
result = [
user1: {
192.168.98.0/26
map[
xx.user1.domain.com: {192.168.98.1 good}
xx.user1.domain.com: {192.168.98.3 good}
xx.user1.domain.com: {192.168.98.4 Bad}
]
}
user2: {
192.168.99.0/26
map[
xx.user2.domain.com: {192.168.99.1 good}
]
}
]
如何遍历这个JSON,以获取特定用户的状态为"good"的ip地址?
我尝试这样做:
for j, _ := range result["user1"].Host {
if a := result["user1"].Host[j].Status; a == "good" {
//问题在于我不确定如何进一步扫描ip和状态
//做一些操作
}
}
希望对你有帮助!
英文:
I am new to Golang:
These are my defined struct:
type Name map[string]Info
type Info struct {
Addresses string `json:"addresses"`
Host map[string]Server `json:"host"`
}
type Server struct {
Ipaddress string `json:"ip"`
Status string `json:"status"`
}
var result Name
after unmarshalling Json i get:
result = [
user1:{
192.168.98.0/26
map[
xx.user1.domain.com:{192.168.98.1 good}
xx.user1.domain.com:{192.168.98.3 good}
xx.user1.domain.com:{192.168.98.4 Bad}
]
}
user2: {
192.168.99.0/26
map[
xx.user2.domain.com:{192.168.99.1 good}
]
}
]
How to range over this Json to get the ipaddress which has a status=="good" for the particular user ?
I am trying to do this way:
for j , _ := range result["user1"].Servers {
if a := result["user1"].Servers[j]); a == "good" {
//Problem is here I am not sure how to further scan the ip and status
//do something
}
}
}
答案1
得分: 2
我认为你想要的是:
for _ , i := range result {
for _, j := range i.Host {
if j.Status == "good" {
server := j.Ip
}
}
}
这段代码的作用是遍历result
列表中的元素,然后遍历每个元素中的Host
列表。如果某个Host
的Status
属性等于"good",则将该Host
的Ip
属性赋值给变量server
。
英文:
I think you want:
for _ , i := range result {
for _, j := range i.Host {
if j.Status == "good" {
server := j.Ip
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论