Python .get 嵌套 Json 值

标签 python json rest

我有一个 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/

相关文章:

javascript - Flot 无法上传 JSON

json - cakephp Web服务如何编写允许我上传文件的 Action

python - 哪种稀疏矩阵格式更适合构建分块矩阵

python - 即使已安装 Python 模型(使用 gcloud)也会出现导入错误

python - 如何反转字符串中单词的顺序

python - 将所需数据从一个文件复制到python中的另一个文件

javascript - 正文解析器不从表单读取数据

c++ - 从 C# : WebMessageBodyStyle. Wrapped 或 WebMessageBodyStyle.Bare 生成 JSON?

rest - CherryPy 中的嵌套 RESTful 路由

java - 用于验证的 REST API 中的媒体类型