有没有任何方便的方法来获取不带类型断言的JSON元素? [英] Is there any convenient way to get JSON element without type assertion?

查看:48
本文介绍了有没有任何方便的方法来获取不带类型断言的JSON元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理来自Web服务器的JSON响应时会遇到一些不便.

There is some inconvenience while processing JSON response from a web server.

例如,我不知道JSON的数据结构(也不想对其建模),只是想从中获取值!

For example, I don't know the data structure (and don't want to model it) of the JSON in advance, and just want to get the value from it!

因此,对于Python,我可以编写

So, for Python, I can just write

value = response["body"][4]["data"]["uid"]  //response is a dictionary

但是对于Golang,我需要对每个元素进行断言!

But for Golang, I need to do the assertion for every element!

value := response["body"].([]interface{})[4].(map[string]interface{})["data"].(map[string]interface{})["uid"]
//response is a map[string]interface{}

这就是我用golang编写的代码,以获得所需的值.您对此有什么建议吗?对于这种情况,有什么有用的提示吗?

This is what I write in golang to get the value I need. Do you have any suggestion on it? It there any useful tips for this kind of case?

推荐答案

如果使用struct对JSON对象建模,并解组为该对象的值,则不需要这些难看的索引和类型断言,则可以只需引用struct字段即可.
注意,您不必担心响应会很复杂,只需要对要使用的零件建模即可.例如.如果响应是一个具有一百个字段的对象,但您只需要2个,则创建一个仅包含这两个字段的结构.

If you model your JSON object with a struct and you unmarshal into a value of that, then you don't need those ugly indices and type assertions, you can simply refer to struct fields.
Note that you don't have to be afraid of the response being complex, you only need to model the parts you intend to use. E.g. if the response is an object with a hundred fields but you only need 2, then create a struct containing only those 2 fields.

如果您不想为JSON对象建模(或者因为它是动态的而不能建模),则可以编写一个通用的实用函数,该函数基于 path (映射键和切片索引),您可以在此答案中看到:

If you don't want to model your JSON object (or can't because it's dynamic), then you may write a general utility function which gets a value based on the path (series of map keys and slice indices), which you can see in this answer: Taking a JSON string, unmarshaling it into a map[string]interface{}, editing, and marshaling it into a []byte seems more complicated then it should be

最后,您可以使用已经包含此帮助程序功能的第三方库,例如 https://github.com/icza/dyno (披露:我是作者).

And last you may use 3rd party libs which already contain this helper functionality, such as https://github.com/icza/dyno (disclosure: I'm the author).

使用 github.com/icza/dyno ,它看起来像这样:

Using github.com/icza/dyno, it would look like this:

value, err := dyno.Get(response, "body", 4, "data", "uid")

这篇关于有没有任何方便的方法来获取不带类型断言的JSON元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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