如何在GOLANG

时间:2017-02-06 21:26:34

标签: arrays json go

我有以下json哈希的json数组:

[
  {
    "name": "XXXX",
    "address": "XXXX",
    "keepalive": {
      "thresholds": {
        "warning": 30,
        "critical": 100
      },
      "handlers": [
        "XXXXX"
      ],
      "refresh": 180
    },
    "subscriptions": [
      "XXXX",
      "XXXX",
      "XXXX"
    ],
    "version": "0.17.1",
    "timestamp": 1486413490
  },
  {...}, 
  {...},
...
]

我正在解析数组如下:

type Client struct {
    Name string `json:"name"`
    Address string `json:"address"`
    PublicDNS string `json:"publicDNS"`
    keepalive [] string `json:"keepalive"`
    Subscriptions [] string `json:"subscriptions"`
    Version string `json:"version"`
    Timestamp int64 `json:"timestamp"`
}

type ClientResponse []Client


func getClients(body []byte) (*ClientResponse, error) {
    var s = new(ClientResponse)
    err := json.Unmarshal(body, &s)
    if(err != nil){
        fmt.Println("whoops:", err)
    }
    return s, err
}


func main() {
    res,err := http.Get("http://xxxxx:4567/clients")
    if err != nil{
        panic(err.Error())
    }

    body,err := ioutil.ReadAll(res.Body)
    if err != nil{
        panic(err.Error())
    }
    s, err := getClients([]byte(body))  
    fmt.Println(s)
}

问题:变量s,包含所有数组。所以我怎么能得到所有数组的名称值?我应该做循环并获得我需要的价值吗?这是最好的方法吗?

1 个答案:

答案 0 :(得分:1)

你必须循环它们。

names := make([]string, len(*s))
for i := range *s {
    names[i] = (*s)[i].Name
}

顺便提一下,您的解组结构不正确。 keepalive未导出,因此它不会被解组,即使它是,它也被定义为一个字符串片段,而JSON中的keepalive字段是{{1}的对象}},thresholdshandlers字段