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

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

How to range over nested struct in golang?

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对Golang还不熟悉:
这是我定义的结构体:

  1. type Name map[string]Info
  2. type Info struct {
  3. Addresses string `json:"addresses"`
  4. Host map[string]Server `json:"host"`
  5. }
  6. type Server struct {
  7. Ipaddress string `json:"ip"`
  8. Status string `json:"status"`
  9. }
  10. var result Name

在解析JSON后,我得到了:

  1. result = [
  2. user1: {
  3. 192.168.98.0/26
  4. map[
  5. xx.user1.domain.com: {192.168.98.1 good}
  6. xx.user1.domain.com: {192.168.98.3 good}
  7. xx.user1.domain.com: {192.168.98.4 Bad}
  8. ]
  9. }
  10. user2: {
  11. 192.168.99.0/26
  12. map[
  13. xx.user2.domain.com: {192.168.99.1 good}
  14. ]
  15. }
  16. ]

如何遍历这个JSON,以获取特定用户的状态为"good"的ip地址?

我尝试这样做:

  1. for j, _ := range result["user1"].Host {
  2. if a := result["user1"].Host[j].Status; a == "good" {
  3. //问题在于我不确定如何进一步扫描ip和状态
  4. //做一些操作
  5. }
  6. }

希望对你有帮助!

英文:

I am new to Golang:
These are my defined struct:

  1. type Name map[string]Info
  2. type Info struct {
  3. Addresses string `json:"addresses"`
  4. Host map[string]Server `json:"host"`
  5. }
  6. type Server struct {
  7. Ipaddress string `json:"ip"`
  8. Status string `json:"status"`
  9. }
  10. var result Name

after unmarshalling Json i get:

  1. result = [
  2. user1:{
  3. 192.168.98.0/26
  4. map[
  5. xx.user1.domain.com:{192.168.98.1 good}
  6. xx.user1.domain.com:{192.168.98.3 good}
  7. xx.user1.domain.com:{192.168.98.4 Bad}
  8. ]
  9. }
  10. user2: {
  11. 192.168.99.0/26
  12. map[
  13. xx.user2.domain.com:{192.168.99.1 good}
  14. ]
  15. }
  16. ]

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:

  1. for j , _ := range result["user1"].Servers {
  2. if a := result["user1"].Servers[j]); a == "good" {
  3. //Problem is here I am not sure how to further scan the ip and status
  4. //do something

}

  1. }
  2. }

答案1

得分: 2

我认为你想要的是:

  1. for _ , i := range result {
  2. for _, j := range i.Host {
  3. if j.Status == "good" {
  4. server := j.Ip
  5. }
  6. }
  7. }

这段代码的作用是遍历result列表中的元素,然后遍历每个元素中的Host列表。如果某个HostStatus属性等于"good",则将该HostIp属性赋值给变量server

英文:

I think you want:

  1. for _ , i := range result {
  2. for _, j := range i.Host {
  3. if j.Status == "good" {
  4. server := j.Ip
  5. }
  6. }
  7. }

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:

确定