douxin8749 2019-02-12 20:45
浏览 167
已采纳

Python像使用Golang的json处理

Using Python I can do following:

r = requests.get(url_base + url)
jsonObj = json.loads(r.content.decode('raw_unicode_escape'))
print(jsonObj["PartDetails"]["ManufacturerPartNumber"]

Is there any way to perform same thing using Golang? Currently I need following:

json.Unmarshal(body, &part_number_json)
fmt.Println("
PartDetails: ", part_number_json.(map[string]interface{})["PartDetails"].(map[string]interface{})["ManufacturerPartNumber"])

That is to say I need to use casting for each field of JSON what tires and makes the code unreadable. I tried this using reflection but it is not comphortable too.

EDIT: currently use following function:

func jso(json interface{}, fields ...string) interface{} {
    res := json
    for _, v := range fields {
        res = res.(map[string]interface{})[v]
    }
    return res

and call it like that:

fmt.Println("PartDetails: ", jso( part_number_json, "PartDetails", "ManufacturerPartNumber") )
  • 写回答

2条回答 默认 最新

  • dongzhuoxie1244 2019-02-12 20:58
    关注

    There are third-party packages like gjson that can help you do that.

    That said, note that Go is Go, and Python is Python. Go is statically typed, for better and worse. It takes more code to write simple JSON manipulation, but that code should be easier to maintain later since it's more strictly typed and the compiler helps you check against error. Types also serve as documentation - simply nesting dicts and arrays is completely arbitrary.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示