![](/img/trans.png)
[英]Loop prints multiple lines (as intended) but only writes one line to the file
[英]For loop only writes one object into a JSON file
我正在尝试遍历 JSON 文件并将特定键值写入新的 JSON 文件:
def get_rubrik_failed_archives_main():
with open("get_failed_archives.json") as json_file:
json_data = json.load(json_file)
for archive_data in json_data["data"]:
dictionary = {
"objectName": archive_data["latestEvent"]["objectName"],
"time": archive_data["latestEvent"]["time"],
"eventType": archive_data["latestEvent"]["eventType"],
"eventStatus": archive_data["latestEvent"]["eventStatus"]
}
with open("rubrik_failed_archives.json", "w") as file:
json.dump(dictionary, file, indent=4, sort_keys=True)
问题是我似乎无法将多个对象写入 JSON 文件,因为我只得到一个 object:
{
"eventStatus": "Failure",
"eventType": "Archive",
"objectName": "Template",
"time": "2022-08-21T16:09:31.863Z"
}
如何编写一个 for 循环,以便将所有需要的键值写入新的 JSON 文件?
似乎无法在字典中更新新数据。
所以,我想出的答案是json_data.update(dictionary)
添加到 for 循环中。
def get_rubrik_failed_archives_main():
with open("get_failed_archives.json") as json_file:
json_data = json.load(json_file)
for archive_data in json_data["data"]:
dictionary = {
"objectName": archive_data["latestEvent"]["objectName"],
"time": archive_data["latestEvent"]["time"],
"eventType": archive_data["latestEvent"]["eventType"],
"eventStatus": archive_data["latestEvent"]["eventStatus"]
}
json_data.update(dictionary)
with open("rubrik_failed_archives.json", "w") as file:
json.dump(dictionary, file, indent=4, sort_keys=True)
我不知道它是否会解决,因为我无法检查它,但我希望它可以帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.