场景:
考虑以下是JSON:
{
"Bangalore_City": "35_Temperature",
"NewYork_City": "31_Temperature",
"Copenhagen_City": "29_Temperature"
}
Run Code Online (Sandbox Code Playgroud)
如果您注意到,数据的结构使得没有硬编码的密钥提及City/ Temperature它基本上只是值.
问题:我无法解析任何动态的JSON.
问题:有没有人能找到这种JSON解析的解决方案?我试过go-simplejson,gabs和默认encoding/json但没有运气.
注意: 上面的JSON仅用于示例.并且有很多应用程序正在使用当前的API,所以我不想改变数据的结构.我的意思是我不能改变如下:
[{
"City_Name":"Bangalore",
"Temperature": "35"
},...]
Run Code Online (Sandbox Code Playgroud)
然后我可以定义 struct
type TempData struct {
City_Name string
Temperature string
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个可以像这样处理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
}]
}
}
Run Code Online (Sandbox Code Playgroud)
因为每次键都不一样......不同的响应可能有更多或更少的键,不同的键,并且正如您所看到的,50x100返回特定大小的多个图像,如何创建与此匹配的结构?
我可以这样做:
type ImageURL struct {
Url string
Width, Height int
}
Run Code Online (Sandbox Code Playgroud)
对于单个项目,以及特定键的列表.但是包含结构看起来如何?
就像是:
type Images struct {
50x100 []ImageURL
...
}
type Items struct {
name string
Image_Urls []Images
}
Run Code Online (Sandbox Code Playgroud)
可能会工作,但我无法枚举所有可能的图像大小响应.此外,Image_Urls最后还没有真正的列表.如果可能的话,我希望能够将它直接转储到json.Unmarshal中.