如何解析/激活Golang中的动态JSON [英] How to parse/deserlize a dynamic JSON in Golang
问题描述
> {
Bangalore_City:35_Temperature,
NewYork_City:31_Temperature,
Copenhagen_City:29_Temperature
}
$ c如果您注意到,数据的结构是这样的,即没有硬编码的密钥提及城市
/ code> / 温度
其基本上只是数值。
问题:我无法解析任何动态的JSON。
问题:任何人都可以找到这种JSON解析的解决方案吗?我尝试了 go-simplejson , gabs &默认 encoding / json
但没有运气。
注意:
上面的JSON仅供参考。而且有很多应用程序正在使用当前的API,所以我不想改变数据的结构。我的意思是我不能改变如下:
[{
City_Name:Bangalore,
温度:35
},...]
然后我可以定义 struct
类型TempData结构{
City_Name字符串
温度字符串
}
解决方案 <例如:您可以解组为 map [字符串]字符串
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 。
这种方式不管wha你可以在 map
中打印或循环所有对。
还要注意,尽管你的例子只包含 string
值,但是如果值类型不同(例如 string
,数字等),您可以使用 interface {}
作为值类型,在这种情况下,您的地图会可以是 map [string]接口{}
。
另外请注意,我创建了一个库来轻松处理这些动态对象可能对这些情况有很大帮助: github.com/icza/dyno
。
Scenario:
Consider the following is the JSON :
{
"Bangalore_City": "35_Temperature",
"NewYork_City": "31_Temperature",
"Copenhagen_City": "29_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.
Issue: I am not able to parse any JSON which is dynamic.
Question: Could anyone have found solution for this kind of JSON parsing? I tried go-simplejson, gabs & default encoding/json
but no luck.
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"
},...]
Then I can define struct
type TempData struct {
City_Name string
Temperature 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)
Output (wrapped):
map[Bangalore_City:35_Temperature NewYork_City:31_Temperature
Copenhagen_City:29_Temperature]
Try it on the Go Playground.
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.
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{}
.
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
.
这篇关于如何解析/激活Golang中的动态JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!