Python .get 嵌套 JSON 值

对于长期使用python写代码的我来说,经常在Python代码中,使用.get方法来访问嵌套在JSON结构中的值。我们知道JSON(JavaScript Object Notation)是一种常见的数据交换格式,它可以包含嵌套的键值对。但是在我们使用总该如何获取嵌套对象中的值呢?

1、问题背景

在 Python 中,可以使用 .get() 方法从 JSON 对象中获取值。当 JSON 对象中嵌套了其他 JSON 对象时,如何获取嵌套对象中的值呢?

例如,以下 JSON 对象中包含了一个名为 "product" 的嵌套对象,该对象又包含了几个子对象。

bash 复制代码
{
            "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"
        }

如果要获取 "product" 对象中的 "offerPrice" 值,可以使用以下代码:

csharp 复制代码
entry.get("product").get("offerPrice")

这样就可以获取到 "offerPrice" 的值 "$19.95"。

2、解决方案

但是,如果 JSON 对象中的嵌套对象不是直接使用键值对表示,而是使用数组表示,则获取嵌套对象中的值就会变得更加复杂。

例如,以下 JSON 对象中包含了一个名为 "media" 的嵌套数组,该数组中包含了多个子对象。

bash 复制代码
{
    "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]"
            },
            {
                "link": "http://www.test.com/cool2.jpg",
                "primary": false,
                "type": "image",
                "xpath": "/html[1]/body[1]/div[1]/div[3]/div[2]/div[1]/div[1]/div[1]/div[1]/a[2]/img[1]"
            }
        ],
        "availability": true
    },
    "human_language": "en",
    "url": "http://www.test.com"
}

如果要获取 "media" 数组中的第一个子对象中的 "link" 值,可以使用以下代码:

csharp 复制代码
entry.get("product", {}).get("media", [])[0].get("link")

这样就可以获取到第一个子对象的 "link" 值 "www.test.com/cool.jpg"。

代码示例

kotlin 复制代码
import json
​
# 读取 JSON 文件
with open('data.json', 'r') as f:
    data = json.load(f)
​
# 获取 "product" 对象中的 "offerPrice" 值
offer_price = data.get("product", {}).get("offerPrice")
​
# 获取 "media" 数组中的第一个子对象的 "link" 值
media_link = data.get("product", {}).get("media", [])[0].get("link")
​
# 打印获取到的值
print("Offer price:", offer_price)
print("Media link:", media_link)

在这个例子中,.get方法用于安全地获取字典中的值,即使某个键不存在也不会导致程序崩溃。如果嵌套结构中有可能缺少某些键,可以使用.get方法来避免KeyError。

请注意,第二个参数是.get方法的默认值,如果指定键不存在,则返回这个默认值。在这个例子中,我们使用{}作为默认值,以确保即使嵌套的"address"键不存在,我们仍然可以安全地调用.get("address", {}).get("city")而不会导致错误。

总的来说只要注意默认值以及语法使用是一点问题没有。如果大家有啥问题可以留言讨论。

相关推荐
NeoGressAI外贸数字化2 天前
外贸独立站robots.txt怎么写:6个AI爬虫放行规则
人工智能·爬虫
OnlineProxy2 天前
移动应用数据爬取:通过模拟器与流量嗅探对 API 进行逆向工程
爬虫·python·httpx
傻啦嘿哟2 天前
分布式爬虫架构:Redis+Scrapy打造企业级爬虫系统
分布式·爬虫·架构
梯度下降者2 天前
零基础入门Python 爬虫
爬虫·python·数据分析·入门指南·webcrawler
2601_967979123 天前
0 到 1 学爬虫:用 Python 爬取网页数据指南一(附实战案例)
爬虫·python·实战案例·html解析·网页数据
姚瑞南3 天前
【PRD】招投标商机雷达爬虫系统
人工智能·经验分享·笔记·爬虫·产品运营·产品经理
嫂子的姐夫4 天前
055-wasm:爬虫练习网spa15(token 纯算还原)
爬虫·wasm
深蓝电商API4 天前
用AI生成拟人行为:让鼠标轨迹更“有人味”
人工智能·爬虫
深蓝电商API4 天前
XPath、CSS选择器、正则:什么场景用什么
爬虫·xpath·css选择器
陶醉的松鼠5 天前
SCRAPY爬虫框架使用详述
爬虫