如何用Python将第一个JSON文件的text内容替换为第二个JSON的内容?
Python实现替换JSON对象的text字段内容
实现思路
读取两个JSON文件的内容,将第一个JSON中每个对象的text字段替换为第二个JSON对应索引对象的text值,保留第一个JSON原有的section数组,最后将修改后的内容保存(建议另存为新文件,避免覆盖原数据)。
完整代码示例
import json # 定义文件路径,根据实际情况修改 first_json_path = "first_file.json" second_json_path = "second_file.json" output_path = "modified_first_file.json" try: # 读取第一个JSON文件 with open(first_json_path, "r", encoding="utf-8") as f1: first_data = json.load(f1) # 读取第二个JSON文件 with open(second_json_path, "r", encoding="utf-8") as f2: second_data = json.load(f2) # 检查两个JSON的对象数量是否匹配 if len(first_data) != len(second_data): raise ValueError("两个JSON文件中的对象数量不匹配,无法完成替换") # 替换每个对象的text字段 for idx in range(len(first_data)): # 保留原section数组,替换text为第二个JSON对应对象的值 first_data[idx]["text"] = second_data[idx]["text"] # 将修改后的内容写入文件 with open(output_path, "w", encoding="utf-8") as out_f: json.dump(first_data, out_f, ensure_ascii=False, indent=4) print(f"替换完成,结果已保存到 {output_path}") except FileNotFoundError as e: print(f"错误:未找到文件 - {e.filename}") except json.JSONDecodeError: print("错误:JSON文件格式无效,请检查文件内容") except ValueError as e: print(f"错误:{e}")
关键说明
- 路径修改:请根据实际文件位置调整
first_json_path、second_json_path和output_path的取值 - 编码兼容:使用
encoding="utf-8"确保支持法语等多语言字符,ensure_ascii=False避免输出时转义特殊字符 - 数据安全:示例将结果保存到新文件,避免意外覆盖原始数据;若需直接覆盖原文件,可将
output_path设置为first_json_path - 异常排查:代码包含了文件缺失、JSON格式错误、对象数量不匹配等常见问题的捕获逻辑,便于快速定位问题
内容的提问来源于stack exchange,提问作者jori
相关产品推荐
相关产品推荐

