2017-07-25 46 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 
     } 
    } 
}