在Python中,处理嵌套的JSON数据非常简单
import json
# 示例嵌套 JSON 数据
nested_json = '''
{
"name": "John",
"age": 30,
"city": "New York",
"hobbies": [
"reading",
"traveling",
{
"type": "sports",
"name": "basketball"
}
]
}
'''
# 将 JSON 字符串解析为 Python 字典
data = json.loads(nested_json)
# 访问嵌套 JSON 数据
name = data["name"]
age = data["age"]
city = data["city"]
hobbies = data["hobbies"]
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
print(f"Hobbies: {hobbies}")
# 访问嵌套的兴趣爱好
for hobby in hobbies:
if isinstance(hobby, list):
for item in hobby:
if isinstance(item, dict):
print(f"Nested hobby type: {item['type']}, name: {item['name']}")
else:
print(f"Hobby: {item}")
else:
print(f"Hobby: {hobby}")
在这个示例中,我们首先导入了json
模块,然后定义了一个包含嵌套JSON数据的字符串nested_json
。接下来,我们使用json.loads()
函数将JSON字符串解析为Python字典。最后,我们通过访问字典的键来获取嵌套的JSON数据,并使用isinstance()
函数来检查数据的类型。