溫馨提示×

Python怎么取json中嵌套數(shù)據(jù)

小億
291
2023-08-11 22:36:51
欄目: 編程語言

要獲取嵌套在JSON中的數(shù)據(jù),可以使用Python的json庫和字典的索引操作。

首先,使用json.loads()函數(shù)將JSON字符串解析為Python字典對象。然后,就可以使用字典的索引操作來提取嵌套在JSON中的數(shù)據(jù)。

以下是一個示例代碼,演示如何使用Python來提取嵌套在JSON中的數(shù)據(jù):

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中的數(shù)據(jù)
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)

輸出結(jié)果:

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

在上面的示例中,我們首先使用json.loads()函數(shù)將JSON字符串解析為Python字典對象。然后,我們使用字典的索引操作來提取嵌套在JSON中的數(shù)據(jù)。例如,data["name"]表示獲取字典data中鍵為"name"的值,data["education"]["degree"]表示獲取字典data中鍵為"education"的值,再獲取這個值中鍵為"degree"的值。

0