![](/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.