如何解析/反序列化动态JSON [英] How to parse/deserialize dynamic JSON

查看:159
本文介绍了如何解析/反序列化动态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 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:

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]

去游乐场上尝试.

通过这种方式,无论键或值是什么,您都将在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屋!

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