dongyijing2353 2018-01-22 08:38
浏览 47
已采纳

是否有任何便捷的方法来获取没有类型断言的JSON元素?

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

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!

So, for Python, I can just write

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

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{}

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?

  • 写回答

2条回答 默认 最新

  • dqkmn26444 2018-01-22 08:41
    关注

    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.

    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

    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).

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

    value, err := dyno.Get(response, "body", 4, "data", "uid")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题