如何用Python从列表加载多个JSON文件并分别提取指定值?
解决JSON文件循环加载后仅保留最后一个数据的问题
问题根源
你写的循环里,每次加载JSON都会覆盖data变量,所以循环结束后data只会留存最后一个文件的内容。要提取每个文件的特定值,必须在每次循环内部就处理当前文件的数据,而非等循环结束后再操作。
具体解决方案
假设你需要提取每个JSON文件中的"key"字段值,以下是几种实用的实现方式:
1. 提取后直接处理(无需保存)
如果不需要留存所有值,直接在循环内对当前文件的目标值做处理(比如打印、传入业务函数):
import json json_files = ['file1.json', 'file2.json', 'file3.json'] for file_path in json_files: with open(file_path, "r") as f: data = json.load(f) # 提取目标键值并处理 target_value = data["key"] print(f"文件[{file_path}]的key值:{target_value}") # 调用你的业务函数,示例:your_business_func(target_value)
2. 保存所有提取的值到容器
如果需要后续统一处理所有文件的目标值,可以用列表或字典存储:
import json json_files = ['file1.json', 'file2.json', 'file3.json'] # 用列表按顺序存储所有值 all_target_values = [] # 或者用字典关联文件名与对应值:all_target_values = {} for file_path in json_files: with open(file_path, "r") as f: data = json.load(f) target_value = data["key"] all_target_values.append(target_value) # 字典存储方式:all_target_values[file_path] = target_value # 后续遍历容器处理所有值 for idx, value in enumerate(all_target_values): print(f"第{idx+1}个文件的key值:{value}")
3. 兼容异常情况的稳健写法
如果部分JSON文件可能缺失目标键、格式无效或文件不存在,建议添加异常处理避免程序崩溃:
import json json_files = ['file1.json', 'file2.json', 'file3.json'] for file_path in json_files: try: with open(file_path, "r") as f: data = json.load(f) target_value = data["key"] print(f"文件[{file_path}]的key值:{target_value}") except KeyError: print(f"文件[{file_path}]中不存在'key'字段") except json.JSONDecodeError: print(f"文件[{file_path}]不是有效的JSON格式") except FileNotFoundError: print(f"未找到文件[{file_path}]")
内容的提问来源于stack exchange,提问作者john
相关产品推荐
相关产品推荐

