遍历嵌套的JSON结构

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

Traversing nested JSON structs

问题

我想遍历嵌套的JSON结构并从interface{}中获取每个键和值。

以下是要翻译的代码部分:

  1. 我想从以下结构中获取
  2. {
  3. "tg": {
  4. "A": {
  5. "E": 100,
  6. "H": 14
  7. },
  8. "B": {
  9. "D": 1
  10. },
  11. "C": {
  12. "D": 1,
  13. "E": 1
  14. },
  15. "D": {
  16. "F": 1,
  17. "G": 1,
  18. "H": 1
  19. },
  20. "E": {
  21. "G": 1
  22. }
  23. }
  24. }
  25. 我能够获取以下内容
  26. a := js.Get("tg").Get("D").Get("F")
  27. fmt.Println(*a) // {1}
  28. 但是在将其类型断言为整数时遇到了问题
  29. invalid type assertion: (*a).(int)
  30. 如何遍历整个结构并获取每个字符映射的整数
  31. 谢谢

以下是翻译好的内容:

我想遍历嵌套的JSON结构并从interface{}中获取每个键和值。

以下是要翻译的代码部分:

  1. 我想从以下结构中获取
  2. {
  3. "tg": {
  4. "A": {
  5. "E": 100,
  6. "H": 14
  7. },
  8. "B": {
  9. "D": 1
  10. },
  11. "C": {
  12. "D": 1,
  13. "E": 1
  14. },
  15. "D": {
  16. "F": 1,
  17. "G": 1,
  18. "H": 1
  19. },
  20. "E": {
  21. "G": 1
  22. }
  23. }
  24. }
  25. 我能够获取以下内容
  26. a := js.Get("tg").Get("D").Get("F")
  27. fmt.Println(*a) // {1}
  28. 但是在将其类型断言为整数时遇到了问题
  29. invalid type assertion: (*a).(int)
  30. 如何遍历整个结构并获取每个字符映射的整数
  31. 谢谢
英文:

I want to traverse the nested JSON struct and get each key and value from the interface{}

http://play.golang.org/p/B-B3pejGJW

So I want from the following struct

  1. {
  2. "tg": {
  3. "A": {
  4. "E": 100,
  5. "H": 14
  6. },
  7. "B": {
  8. "D": 1
  9. },
  10. "C": {
  11. "D": 1,
  12. "E": 1
  13. },
  14. "D": {
  15. "F": 1,
  16. "G": 1,
  17. "H": 1
  18. },
  19. "E": {
  20. "G": 1
  21. }
  22. }
  23. }

I was able to get the following

  1. a := js.Get("tg").Get("D").Get("F")
  2. fmt.Println(*a) // {1}

but having trouble with type assert this to integer.

  1. invalid type assertion: (*a).(int)

How would would traverse this whole struct and get each integer mapped from the characters?

Thanks!

答案1

得分: 1

你的值将被转换为 float64 类型。此外,你没有访问 a.data,而是访问了一个结构体 a,这导致了错误。

  1. fmt.Printf("%#v\n", a) // &main.JSON{data:1}
  2. fmt.Println(reflect.TypeOf(a.data)) // float64
  3. x := int(a.data.(float64))
英文:

Your value will be marshalled into a float64. Plus you are not accessing a.data but a instead which is a struct which is causing the error.

  1. fmt.Printf("%#v\n", a) // &main.JSON{data:1}
  2. fmt.Println(reflect.TypeOf(a.data)) // float64
  3. x := int(a.data.(float64))

huangapple
  • 本文由 发表于 2014年3月6日 14:40:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/22217019.html
匿名

发表评论

匿名网友

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

确定