Python循环写入JSON文件仅生成单个对象的问题及解决
问题原因
你的代码中每次循环都以写入模式("w")打开输出文件,该模式会清空文件原有内容并写入当前循环的单个对象,因此最终文件仅保留最后一次循环的结果。
修改方案
正确的做法是先将所有需要的数据收集到一个列表中,再一次性将整个列表写入文件,这样生成的JSON会是合法的数组结构。
修改后的代码如下:
import json # 确保导入json模块,原代码可能遗漏了此步骤 def get_rubrik_failed_archives_main(): # 读取源JSON文件 with open("get_failed_archives.json") as json_file: json_data = json.load(json_file) # 初始化空列表,用于收集所有目标数据对象 failed_archives = [] for archive_data in json_data["data"]: # 构建单个数据对象 archive_entry = { "objectName": archive_data["latestEvent"]["objectName"], "time": archive_data["latestEvent"]["time"], "eventType": archive_data["latestEvent"]["eventType"], "eventStatus": archive_data["latestEvent"]["eventStatus"] } # 将对象添加到列表中 failed_archives.append(archive_entry) # 一次性将整个列表写入输出文件 with open("rubrik_failed_archives.json", "w") as file: json.dump(failed_archives, file, indent=4, sort_keys=True)
效果说明
修改后生成的输出文件会是合法的JSON数组,包含所有符合条件的对象,示例格式如下:
[ { "eventStatus": "Failure", "eventType": "Archive", "objectName": "Template", "time": "2022-08-21T16:09:31.863Z" }, { "eventStatus": "Failure", "eventType": "Archive", "objectName": "SampleObject", "time": "2022-08-22T09:30:15.247Z" } ]
内容的提问来源于stack exchange,提问作者user15565485
相关产品推荐
相关产品推荐

