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

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

golang struct for json with arbitrary keys

问题

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

{"items":
[{"name": "thing",
  "image_urls": {
    "50x100": [{
      "url": "http://site.com/images/1/50x100.jpg",
      "width": 50,
      "height": 100
    }, {
      "url": "http://site.com/images/2/50x100.jpg",
      "width": 50,
      "height": 100
    }],
    "200x300": [{
      "url": "http://site.com/images/1/200x300.jpg",
      "width": 200,
      "height": 300
    }],
    "400x520": [{
      "url": "http://site.com/images/1/400x520.jpg",
      "width": 400,
      "height": 520
    }]
  }
}

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

我可以这样做:

type ImageURL struct {
    Url string
    Width, Height int
}

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

类似于:

type Images struct {
    50x100 []ImageURL
    ...
}
type Items struct {
    name string
    Image_Urls []Images
}

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

英文:

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

{"items":
[{"name": "thing",
  "image_urls": {
    "50x100": [{
      "url": "http://site.com/images/1/50x100.jpg",
      "width": 50,
      "height": 100
    }, {
      "url": "http://site.com/images/2/50x100.jpg",
      "width": 50,
      "height": 100
    }],
    "200x300": [{
      "url": "http://site.com/images/1/200x300.jpg",
      "width": 200,
      "height": 300
    }],
    "400x520": [{
      "url": "http://site.com/images/1/400x520.jpg",
      "width": 400,
      "height": 520
    }]
  }
}

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:

type ImageURL struct {
    Url string
    Width, Height int
}

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

Something like:

type Images struct {
    50x100 []ImageURL
    ...
}
type Items struct {
    name string
    Image_Urls []Images
}

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对我来说更像是一个映射。

type Items map[string][]ImageUrl

应该可以满足你的需求。

英文:

Your json looks more like a map to me.

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:

确定