如何在GOLANG中解析JSON数组和JSON哈希。

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

How to parse JSON Array of JSON Hashes in GOLANG

问题

你可以使用循环来遍历数组中的每个元素,并获取所需的值。在你的代码中,变量s是一个包含所有数组的切片,每个数组都代表一个Client对象。你可以使用循环来遍历s,并访问每个Client对象的Name属性来获取名称值。

以下是一个示例代码片段,展示了如何使用循环获取所有数组中的名称值:

  1. for _, client := range *s {
  2. name := client.Name
  3. fmt.Println(name)
  4. }

在这个示例中,我们使用range关键字来遍历s切片中的每个元素,并将每个元素赋值给变量client。然后,我们可以通过client.Name来访问每个Client对象的名称值,并进行相应的操作。

这是一种常见的方法来处理包含多个对象的数组,并获取特定属性的值。希望对你有帮助!

英文:

i have the following json array of json hashes :

  1. [
  2. {
  3. "name": "XXXX",
  4. "address": "XXXX",
  5. "keepalive": {
  6. "thresholds": {
  7. "warning": 30,
  8. "critical": 100
  9. },
  10. "handlers": [
  11. "XXXXX"
  12. ],
  13. "refresh": 180
  14. },
  15. "subscriptions": [
  16. "XXXX",
  17. "XXXX",
  18. "XXXX"
  19. ],
  20. "version": "0.17.1",
  21. "timestamp": 1486413490
  22. },
  23. {...},
  24. {...},
  25. ...
  26. ]

And am parsing the array as the following :

  1. type Client struct {
  2. Name string `json:"name"`
  3. Address string `json:"address"`
  4. PublicDNS string `json:"publicDNS"`
  5. keepalive [] string `json:"keepalive"`
  6. Subscriptions [] string `json:"subscriptions"`
  7. Version string `json:"version"`
  8. Timestamp int64 `json:"timestamp"`
  9. }
  10. type ClientResponse []Client
  11. func getClients(body []byte) (*ClientResponse, error) {
  12. var s = new(ClientResponse)
  13. err := json.Unmarshal(body, &s)
  14. if(err != nil){
  15. fmt.Println("whoops:", err)
  16. }
  17. return s, err
  18. }
  19. func main() {
  20. res,err := http.Get("http://xxxxx:4567/clients")
  21. if err != nil{
  22. panic(err.Error())
  23. }
  24. body,err := ioutil.ReadAll(res.Body)
  25. if err != nil{
  26. panic(err.Error())
  27. }
  28. s, err := getClients([]byte(body))
  29. fmt.Println(s)
  30. }

Problem : variable s , contain all arrays . so how can i get lets say name value for all arrays ? should i do for loop and get values i need ? is this the best approach ?

答案1

得分: 1

你需要对它们进行循环。

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

顺便说一下,你的反序列化结构是不正确的。keepalive 没有被导出,所以它不会被反序列化,即使它被导出了,它在 JSON 中被定义为一个带有 thresholdshandlersrefresh 字段的对象,而不是一个字符串切片。

英文:

You'll have to loop over them.

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

Incidentally, your structure for unmarshalling is incorrect. keepalive isn't exported, so it won't be unmarshalled, and even if it were, it's defined as a slice of strings, while the keepalive field in the JSON is an object with thresholds, handlers, and refresh fields

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

发表评论

匿名网友

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

确定