Python怎么取json中嵌套数据

852
2023/8/2 22:36:51
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要获取嵌套在JSON中的数据,可以使用Python的json库和字典的索引操作。

首先,使用json.loads()函数将JSON字符串解析为Python字典对象。然后,就可以使用字典的索引操作来提取嵌套在JSON中的数据。

以下是一个示例代码,演示如何使用Python来提取嵌套在JSON中的数据:

import json
# 要解析的JSON字符串
json_str = '{"name": "John", "age": 30, "city": "New York", "education": {"degree": "Bachelor", "school": "ABC University"}}'
# 解析JSON字符串为Python字典
data = json.loads(json_str)
# 提取嵌套在JSON中的数据
name = data["name"]
age = data["age"]
city = data["city"]
degree = data["education"]["degree"]
school = data["education"]["school"]
print("Name:", name)
print("Age:", age)
print("City:", city)
print("Degree:", degree)
print("School:", school)

输出结果:

Name: John
Age: 30
City: New York
Degree: Bachelor
School: ABC University

在上面的示例中,我们首先使用json.loads()函数将JSON字符串解析为Python字典对象。然后,我们使用字典的索引操作来提取嵌套在JSON中的数据。例如,data["name"]表示获取字典data中键为"name"的值,data["education"]["degree"]表示获取字典data中键为"education"的值,再获取这个值中键为"degree"的值。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python中怎么查找指定字符