我有一个 json 文件,其中包含以下示例 json 条目:
{
"title": "Test prod",
"leafPage": true,
"type": "product",
"product": {
"title": "test product",
"offerPrice": "$19.95",
"offerPriceDetails": {
"amount": 19.95,
"text": "$19.95",
"symbol": "$"
},
"media": [
{
"link": "http://www.test.com/cool.jpg",
"primary": true,
"type": "image",
"xpath": "/html[1]/body[1]/div[1]/div[3]/div[2]/div[1]/div[1]/div[1]/div[1]/a[1]/img[1]"
}
],
"availability": true
},
"human_language": "en",
"url": "http://www.test.com"
}
当我使用时,我可以通过 python 脚本将其完美地发布到我的测试服务器:
"text": entry.get("title"),
"url": entry.get("url"),
"type": entry.get("type"),
但是我无法获取以下嵌套项目来上传值,如何构建 python json 调用来获取嵌套的 python json 条目?
我尝试了以下方法,但没有成功,我需要将其作为 .get,因为 json 文件中当前有不同的字段,并且在没有 .get 调用的情况下会出错。
"Amount": entry.get("product"("offerPrice"))
任何有关如何构建嵌套 json 条目的帮助将非常感激。
最佳答案
你需要做:
"Amount": entry.get("product", {}).get("offerPrice")
entry.get("product", {})
返回产品字典(如果没有 product
键,则返回空字典)。
关于Python .get 嵌套 Json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21750618/