Python就像使用Golang处理json一样

use*_*807 2 json go

使用Python我可以执行以下操作:

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

有没有办法使用Golang执行相同的操作?目前我需要以下:

json.Unmarshal(body, &part_number_json)
fmt.Println("\r\nPartDetails: ", part_number_json.(map[string]interface{})["PartDetails"].(map[string]interface{})["ManufacturerPartNumber"])
Run Code Online (Sandbox Code Playgroud)

也就是说我需要为JSON的每个字段使用强制转换轮胎并使代码不可读.我尝试使用反射,但它也不是很容易.

编辑:目前使用以下功能:

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

并称之为:

fmt.Println("PartDetails: ", jso( part_number_json, "PartDetails", "ManufacturerPartNumber") )
Run Code Online (Sandbox Code Playgroud)

Eli*_*sky 9

有像gjson这样的第三方软件包可以帮助你做到这一点.

也就是说,注意Go是Go,Python是Python.Go是静态类型的,无论好坏.编写简单的JSON操作需要更多代码,但该代码应该更容易维护,因为它更严格地键入,编译器可以帮助您检查错误.类型也可以作为文档 - 简单地嵌套dicts和数组是完全任意的.