golang用于具有任意键的JSON的结构体

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

golang struct for json with arbitrary keys

问题

我正在尝试编写一个可以处理像这样的JSON响应的结构类型:

  1. {"items":
  2. [{"name": "thing",
  3. "image_urls": {
  4. "50x100": [{
  5. "url": "http://site.com/images/1/50x100.jpg",
  6. "width": 50,
  7. "height": 100
  8. }, {
  9. "url": "http://site.com/images/2/50x100.jpg",
  10. "width": 50,
  11. "height": 100
  12. }],
  13. "200x300": [{
  14. "url": "http://site.com/images/1/200x300.jpg",
  15. "width": 200,
  16. "height": 300
  17. }],
  18. "400x520": [{
  19. "url": "http://site.com/images/1/400x520.jpg",
  20. "width": 400,
  21. "height": 520
  22. }]
  23. }
  24. }

由于键名每次都不相同...不同的响应可能有更多或更少的键,不同的键,而且如你所见,对于特定大小的50x100返回多个图像,我该如何创建与之匹配的结构?

我可以这样做:

  1. type ImageURL struct {
  2. Url string
  3. Width, Height int
  4. }

对于单个项目,以及特定键的列表。但是包含的结构是什么样的?

类似于:

  1. type Images struct {
  2. 50x100 []ImageURL
  3. ...
  4. }
  5. type Items struct {
  6. name string
  7. Image_Urls []Images
  8. }

可能会起作用,但我无法枚举所有可能的图像大小响应。而且,最后那个Image_Urls并不真正是一个列表。如果可能的话,我希望能够直接将其转换为json.Unmarshal。

英文:

I am trying to write a struct type that can handle a json response like this

  1. {"items":
  2. [{"name": "thing",
  3. "image_urls": {
  4. "50x100": [{
  5. "url": "http://site.com/images/1/50x100.jpg",
  6. "width": 50,
  7. "height": 100
  8. }, {
  9. "url": "http://site.com/images/2/50x100.jpg",
  10. "width": 50,
  11. "height": 100
  12. }],
  13. "200x300": [{
  14. "url": "http://site.com/images/1/200x300.jpg",
  15. "width": 200,
  16. "height": 300
  17. }],
  18. "400x520": [{
  19. "url": "http://site.com/images/1/400x520.jpg",
  20. "width": 400,
  21. "height": 520
  22. }]
  23. }
  24. }

Since the keys are not the same every time... a different response may have more or less keys, different ones, and as you can see with the 50x100 return multiple images for a particular size how can I create a struct that matches this?

I can do like:

  1. type ImageURL struct {
  2. Url string
  3. Width, Height int
  4. }

for an individual item, and a list of them for a particular key. But how does the containing struct look?

Something like:

  1. type Images struct {
  2. 50x100 []ImageURL
  3. ...
  4. }
  5. type Items struct {
  6. name string
  7. Image_Urls []Images
  8. }

Might work, but I can't enumerate all of the possible image size responses. Also that Image_Urls at the end there isn't truly a list. I'd like to be able to dump it right into json.Unmarshal if possible.

答案1

得分: 16

你的json对我来说更像是一个映射。

  1. type Items map[string][]ImageUrl

应该可以满足你的需求。

英文:

Your json looks more like a map to me.

  1. type Items map[string][]ImageUrl

should do what you want.

huangapple
  • 本文由 发表于 2013年4月5日 01:24:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/15817720.html
匿名

发表评论

匿名网友

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

确定