Python如何读取包含多对象的JSON文件并将每个对象单独导出为JSON文件
实现方案
你原有代码里的data = json.dumps(data, indent=4)属于多余操作,json.load已经将源JSON解析为Python字典,直接遍历该字典的键值对即可完成拆分需求。
完整可运行代码
import json import os # 可选:创建单独的输出目录避免文件混乱,exist_ok=True表示目录已存在时不会报错 os.makedirs("output_metadata", exist_ok=True) # 读取源JSON文件,指定utf-8编码避免特殊字符乱码 with open('metadata1.json', 'r', encoding='utf-8') as json_file: data = json.load(json_file) # 遍历字典键值对:键作为文件名,值为对应要导出的单个对象数据 for file_name, item_data in data.items(): # 拼接输出路径,文件名使用对应键加.json后缀 output_path = os.path.join("output_metadata", f"{file_name}.json") # 写入单个JSON文件 with open(output_path, 'w', encoding='utf-8') as out_file: # indent=4保留格式化缩进,ensure_ascii=False保证非ASCII字符正常显示 json.dump(item_data, out_file, indent=4, ensure_ascii=False)
简化版(不需要单独输出目录,直接生成在当前文件夹)
import json with open('metadata1.json', 'r', encoding='utf-8') as json_file: data = json.load(json_file) for file_name, item_data in data.items(): with open(f"{file_name}.json", 'w', encoding='utf-8') as out_file: json.dump(item_data, out_file, indent=4, ensure_ascii=False)
运行后会生成0.json、1.json、2.json三个文件,每个文件内仅包含对应键的对象数据。
内容的提问来源于stack exchange,提问作者coding_clueless
相关产品推荐
相关产品推荐

