Golang在解组后访问嵌套的JSON数组的问题

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

Golang issue with accessing Nested JSON Array after Unmarshalling

问题

我还在学习Go语言的过程中,但在处理JSON响应数组时遇到了问题。每当我尝试访问"objects"数组的嵌套元素时,Go会抛出错误(类型interface {}不支持索引)。

出了什么问题,我如何避免将来犯同样的错误?

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. func main() {
  7. payload := []byte(`{"query": "QEACOR139GID","count": 1,"objects": [{"ITEM_ID": "QEACOR139GID","PROD_CLASS_ID": "BMXCPGRIPS","AVAILABLE": 19}]}`)
  8. var result map[string]interface{}
  9. if err := json.Unmarshal(payload, &result); err != nil {
  10. panic(err)
  11. }
  12. objects := result["objects"].([]interface{})
  13. firstObject := objects[0].(map[string]interface{})
  14. fmt.Println(firstObject["ITEM_ID"])
  15. }

链接:http://play.golang.org/p/duW-meEABJ

编辑:修复了链接。

英文:

I'm still in the learning process of Go but am hitting a wall when it comes to JSON response arrays. Whenever I try to access a nested element of the "objects" array, Go throws (type interface {} does not support indexing)

What is going wrong and how can I avoid making this mistake in the future?

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. func main() {
  7. payload := []byte(`{"query": "QEACOR139GID","count": 1,"objects": [{"ITEM_ID": "QEACOR139GID","PROD_CLASS_ID": "BMXCPGRIPS","AVAILABLE": 19}]}`)
  8. var result map[string]interface{}
  9. if err := json.Unmarshal(payload, &result); err != nil {
  10. panic(err)
  11. }
  12. fmt.Println(result["objects"]["ITEM_ID"])
  13. }

http://play.golang.org/p/duW-meEABJ

edit: Fixed link

答案1

得分: 28

根据错误提示,接口变量不支持索引。你需要使用类型断言将其转换为底层类型。

在解码为interface{}变量时,JSON模块将数组表示为[]interface{}切片,将字典表示为map[string]interface{}映射。

如果没有错误检查,你可以使用以下代码深入到这个JSON中:

  1. objects := result["objects"].([]interface{})
  2. first := objects[0].(map[string]interface{})
  3. fmt.Println(first["ITEM_ID"])

如果类型不匹配,这些类型断言将会引发恐慌。你可以使用两个返回值的形式来检查错误。例如:

  1. objects, ok := result["objects"].([]interface{})
  2. if !ok {
  3. // 在这里处理错误
  4. }

如果JSON遵循已知的格式,更好的解决方案是解码为一个结构体。根据你的示例数据,以下代码可能适用:

  1. type Result struct {
  2. Query string `json:"query"`
  3. Count int `json:"count"`
  4. Objects []struct {
  5. ItemId string `json:"ITEM_ID"`
  6. ProdClassId string `json:"PROD_CLASS_ID"`
  7. Available int `json:"AVAILABLE"`
  8. } `json:"objects"`
  9. }

如果你解码为这种类型,可以通过result.Objects[0].ItemId访问项目ID。

英文:

As the error says, interface variables do not support indexing. You will need to use a type assertion to convert to the underlying type.

When decoding into an interface{} variable, the JSON module represents arrays as []interface{} slices and dictionaries as map[string]interface{} maps.

Without error checking, you could dig down into this JSON with something like:

  1. objects := result["objects"].([]interface{})
  2. first := objects[0].(map[string]interface{})
  3. fmt.Println(first["ITEM_ID"])

These type assertions will panic if the types do not match. You can use the two-return form, you can check for this error. For example:

  1. objects, ok := result["objects"].([]interface{})
  2. if !ok {
  3. // Handle error here
  4. }

If the JSON follows a known format though, a better solution would be to decode into a structure. Given the data in your example, the following might do:

  1. type Result struct {
  2. Query string `json:"query"`
  3. Count int `json:"count"`
  4. Objects []struct {
  5. ItemId string `json:"ITEM_ID"`
  6. ProdClassId string `json:"PROD_CLASS_ID"`
  7. Available int `json:"AVAILABLE"`
  8. } `json:"objects"`
  9. }

If you decode into this type, you can access the item ID as result.Objects[0].ItemId.

答案2

得分: 0

对于那些可能正在寻找与我类似解决方案的人,https://github.com/Jeffail/gabs 提供了更好的解决方案。

我在这里提供一个示例。

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/Jeffail/gabs"
  6. )
  7. func main() {
  8. payload := []byte(`{
  9. "query": "QEACOR139GID",
  10. "count": 1,
  11. "objects": [{
  12. "ITEM_ID": "QEACOR139GID",
  13. "PROD_CLASS_ID": "BMXCPGRIPS",
  14. "AVAILABLE": 19,
  15. "Messages": [{
  16. "first": {
  17. "text": "sth, 1st"
  18. }
  19. },
  20. {
  21. "second": {
  22. "text": "sth, 2nd"
  23. }
  24. }
  25. ]
  26. }]
  27. }`)
  28. fmt.Println("使用 gabs:")
  29. jsonParsed, _ := gabs.ParseJSON(payload)
  30. data := jsonParsed.Path("objects").Data()
  31. fmt.Println(" 获取数据:")
  32. fmt.Println(" ", data)
  33. children, _ := jsonParsed.Path("objects").Children()
  34. fmt.Println(" 从\"objects\"获取的子数组:")
  35. for key, child := range children {
  36. fmt.Println(" ", key, ":", child)
  37. children2, _ := child.Path("Messages").Children()
  38. fmt.Println(" 从\"Messages\"获取的子数组:")
  39. for key2, child2 := range children2 {
  40. fmt.Println(" ", key2, ":", child2)
  41. }
  42. }
  43. }
英文:

For who those might looking for similar solution like me, https://github.com/Jeffail/gabs provides better solution.

I provide the example here.

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/Jeffail/gabs"
  6. )
  7. func main() {
  8. payload := []byte(`{
  9. "query": "QEACOR139GID",
  10. "count": 1,
  11. "objects": [{
  12. "ITEM_ID": "QEACOR139GID",
  13. "PROD_CLASS_ID": "BMXCPGRIPS",
  14. "AVAILABLE": 19,
  15. "Messages": [ {
  16. "first": {
  17. "text": "sth, 1st"
  18. }
  19. },
  20. {
  21. "second": {
  22. "text": "sth, 2nd"
  23. }
  24. }
  25. ]
  26. }]
  27. }`)
  28. fmt.Println("Use gabs:")
  29. jsonParsed, _ := gabs.ParseJSON(payload)
  30. data := jsonParsed.Path("objects").Data()
  31. fmt.Println(" Fetch Data: ")
  32. fmt.Println(" ", data)
  33. children, _ := jsonParsed.Path("objects").Children()
  34. fmt.Println(" Children Array from \"Objects\": ")
  35. for key, child := range children {
  36. fmt.Println(" ", key, ": ", child)
  37. children2, _ := child.Path("Messages").Children()
  38. fmt.Println(" Children Array from \"Messages\": ")
  39. for key2, child2 := range children2 {
  40. fmt.Println(" ", key2, ": ", child2)
  41. }
  42. }
  43. }

huangapple
  • 本文由 发表于 2014年6月24日 11:32:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/24377907.html
匿名

发表评论

匿名网友

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

确定