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 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题