使用任意键的json golang结构体 [英] golang struct for json with arbitrary keys

查看:107
本文介绍了使用任意键的json golang结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个可以处理类似json响应的结构类型。

  {items:
[{name:thing,
image_urls:{
50x100:[{
url:http://site.com/images/ 1 / 50x100.jpg,
宽度:50,
高度:100
},{
url:http://site.com/图片/ 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为特定大小返回多个图像一样,我如何创建一个匹配它的结构?



我可以这样做:

 类型ImageURL结构{
网址字符串
宽度,高度int
}

一个特定键的列表。但是,包含结构的外观如何?



类似于:

 类型图像struct {
50x100 [] ImageURL
...
}
类型项目struct {
名称字符串
Image_Urls []图片
}

可能会工作,但我无法枚举所有可能的图像大小响应。此外Image_Urls在结尾处并没有真正的列表。如果可能的话,我希望能够将它转储到json.Unmarshal中。

您的json看起来更像是一张地图给我。

 类型项目map [string] [] ImageUrl 

应该做你想做的。


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.

解决方案

Your json looks more like a map to me.

type Items map[string][]ImageUrl

should do what you want.

这篇关于使用任意键的json golang结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆