如果您的 JSON 文件包含嵌套数组,并希望将其解析为 Python 字典,处理方式与解析包含嵌套对象的 JSON 文件类似。JSON 数组在 Python 中会被解析为列表。以下是处理包含嵌套数组的 JSON 文件的示例:
假设您的 JSON 文件(例如 nested_array_json_file.json
)内容如下:
json
{
"people": [
{
"name": "John Doe",
"age": 30,
"hobbies": [
"reading",
"gaming",
"painting"
]
},
{
"name": "Jane Smith",
"age": 28,
"hobbies": [
"hiking",
"photography",
"cooking"
]
}
]
}
使用 Python 解析并存储为字典(其中包含嵌套列表):
python
import json
# JSON 文件路径
json_file_path = 'nested_array_json_file.json'
# 打开并加载 JSON 文件
with open(json_file_path, 'r', encoding='utf-8') as file:
data_dict = json.load(file)
# 现在 data_dict 是一个包含嵌套列表的 Python 字典,您可以像操作普通字典和列表一样使用它
print(type(data_dict)) # 输出:<class 'dict'>
# 访问嵌套字典和列表中的数据
people_list = data_dict['people']
for person_dict in people_list:
name = person_dict['name']
age = person_dict['age']
hobbies = person_dict['hobbies']
print(f'Name: {name}, Age: {age}, Hobbies:')
for hobby in hobbies:
print(f' - {hobby}')
在这个例子中:
json.load(file)
将 JSON 文件内容解析为一个 Python 字典,其中people
键对应的值是一个列表。- 遍历
people_list
,对每个元素(也是一个字典)进行访问,提取name
、age
和hobbies
字段。 - 再次遍历每个
person_dict
中的hobbies
列表,打印出每个人的爱好。
确保 JSON 文件路径正确,并且文件内容是有效的 JSON 格式。解析后的 data_dict
是一个包含嵌套列表的 Python 字典,您可以对其执行常规的字典和列表操作。如果 JSON 数据非常大或复杂,考虑使用流式解析器 json.JSONDecoder
以降低内存消耗。