如何解析/反序列化动态 JSON [英] How to parse/deserialize dynamic JSON
问题描述
场景:
考虑以下是JSON:
Scenario:
Consider the following is the JSON :
{
"Bangalore_City": "35_Temperature",
"NewYork_City": "31_Temperature",
"Copenhagen_City": "29_Temperature"
}
如果您注意到,数据的结构方式没有硬编码键提到 City
/Temperature
基本上只是值.
If you notice, the data is structured in such a way that there is no hard-coded keys mentioning City
/Temperature
its basically just values.
问题:我无法解析任何动态的 JSON.
Issue: I am not able to parse any JSON which is dynamic.
问题: 谁能找到这种 JSON 解析的解决方案?我试过 go-simplejson, gabs &默认 encoding/json
但没有运气.
Question: Could anyone have found solution for this kind of JSON parsing? I tried go-simplejson, gabs & default encoding/json
but no luck.
注意:上面的 JSON 只是示例.并且有很多应用程序都在使用当前的 API,所以我不想改变数据的结构.我的意思是我不能更改为以下内容:
Note: The above JSON is just for sample. And there are lot of applications which are using the current API, So I do not want to change how the data is structured. I mean I can't change to something as follows:
[{
"City_Name":"Bangalore",
"Temperature": "35"
},...]
然后我可以定义struct
type TempData struct {
City_Name string
Temperature string
}
推荐答案
您可以解组为 map[string]string
例如:
You can unmarshal into a map[string]string
for example:
m := map[string]string{}
err := json.Unmarshal([]byte(input), &m)
if err != nil {
panic(err)
}
fmt.Println(m)
输出(包装):
map[Bangalore_City:35_Temperature NewYork_City:31_Temperature
Copenhagen_City:29_Temperature]
在 Go Playground 上试试.
这样,无论键或值是什么,您都将在 map
中拥有所有对,您可以打印或循环遍历.
This way no matter what the keys or values are, you will have all pairs in a map
which you can print or loop over.
另请注意,虽然您的示例仅包含 string
值,但如果值类型变化(例如 string
、数字等),您可以使用 interface{}
用于值类型,在这种情况下,您的地图的类型为 map[string]interface{}
.
Also note that although your example contained only string
values, but if the value type is varying (e.g. string
, numbers etc.), you may use interface{}
for the value type, in which case your map would be of type map[string]interface{}
.
另请注意,我创建了一个库来轻松处理此类动态对象,这在这些情况下可能会有很大帮助:github.com/icza/dyno
.
Also note that I created a library to easily work with such dynamic objects which may be a great help in these cases: github.com/icza/dyno
.
这篇关于如何解析/反序列化动态 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!