2017-07-25 64 views
-4

我是新来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获得具有状态的ip地址= =特别用户的“好”?

我试图做到这一点的方法:

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 

}

} 
} 
+5

你尝试过什么?什么不工作?如果您可以向我们展示您正在使用的代码,请尝试使用可帮助我们引导您的结构。 – Guildencrantz

+0

有'range'或'for'。你没有其他选择。 –

+0

'fmt.Printf()'需要一个字符串和格式,你在你定义的结构体'Server'中传入​​,而不是'string'类型...尝试'fmt.Println()'。 – reticentroot

回答

1

我想你想:

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