如何在Golang中解析嵌套的JSON对象中的嵌套数组?

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

How do I parse a nested array in a nested JSON object in Golang?

问题

我有一个JSON:

  1. {
  2. "data": [
  3. {
  4. "id": 1,
  5. "values": [
  6. [
  7. {
  8. "id": "11",
  9. "keys": [
  10. {
  11. "id": "111"
  12. }
  13. ]
  14. }
  15. ]
  16. ]
  17. }
  18. ]
  19. }

我想将"values"和"keys"解析为结构体,但我不知道在"Data"中应该使用什么类型:

  1. type Value struct {
  2. Id string `json:"id"`
  3. Keys []Key `json:"keys"`
  4. }
  5. type Key struct {
  6. Id string `json:"id"`
  7. }
  8. type Result struct {
  9. Data []Data `json:"data"`
  10. }
  11. type Data struct {
  12. Id int `json:"id"`
  13. Values []Value `json:"values"`
  14. }

感谢任何帮助。谢谢。

英文:

I have a JSON:

  1. {
  2. "data": [
  3. {
  4. "id": 1,
  5. "values": [
  6. [
  7. {
  8. "id": "11",
  9. "keys": [
  10. {
  11. "id": "111"
  12. }
  13. ]
  14. }
  15. ]
  16. ]
  17. }
  18. ]
  19. }

I want to parse "values" and "keys" into structs, but I don't known what type should i use in "Data"?:

  1. type Value struct {
  2. Id string `json:"id"`
  3. Keys []Key `json:"keys"`
  4. }
  5. type Key struct {
  6. Id string `json:"id"`
  7. }
  8. type Result struct {
  9. Data []Data `json:"data"`
  10. }
  11. type Data struct {
  12. Id int `json:"id"`
  13. Values []???? `json:"values"`
  14. }

I would be grateful for any help. Thanks.

答案1

得分: 1

如果仔细查看你的 JSON,你会发现一个数组中嵌套了另一个数组...

  1. ...
  2. "values": [
  3. [...

如果这是你的意图,那么 values 的类型应该是:

  1. [][]Value

表示两个数组,否则请移除数组的嵌套,变成:

  1. []Value

可运行示例: https://play.golang.org/p/UUqQR1KSwB

英文:

If you look carefully at your json. you have an array in an array...

  1. ...
  2. "values": [
  3. [...

If this is intended then the type of values is:

  1. [][]Value

to represent the two arrays, else remove the array nesting and it becomes:

  1. []Value

Runnable Example: https://play.golang.org/p/UUqQR1KSwB

答案2

得分: -1

以下是翻译好的内容:

  1. type Basic struct {
  2. ID string `json:"id"`
  3. }
  4. type Inner struct {
  5. ID string `json:"id"`
  6. Keys []Basic `json:"keys"`
  7. }
  8. type Middle struct {
  9. ID int `json:"id"`
  10. Values []Inner `json:"values"`
  11. }
  12. type Final struct {
  13. Data []Middle `json:"data"`
  14. }
英文:
  1. type Basic struct {
  2. ID string `json:"id"`
  3. }
  4. type Inner struct {
  5. ID string `json:"id"`
  6. Keys []Basic `json:"keys"`
  7. }
  8. type Middle struct {
  9. ID int `json:"id"`
  10. Values []Inner `json:"values"`
  11. }
  12. type Final struct {
  13. Data []Middle `json:"data"`
  14. }

huangapple
  • 本文由 发表于 2017年5月12日 19:11:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/43936400.html
匿名

发表评论

匿名网友

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

确定