如何在Golang中遍历嵌套结构体?

huangapple go评论123阅读模式
英文:

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列表。如果某个HostStatus属性等于"good",则将该HostIp属性赋值给变量server

英文:

I think you want:

for _ , i := range result {
    for  _, j := range i.Host {
        if j.Status == "good" {
            server := j.Ip
        }
    }
}

huangapple
  • 本文由 发表于 2017年7月26日 04:48:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/45313231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定