简体   繁体   English

For 循环仅将一个 object 写入 JSON 文件

[英]For loop only writes one object into a JSON file

I'm trying to iterate over a JSON file and write specific key values to a new 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)

The problem is that I cannot seem to write multiple objects into the JSON file, as I only get one object:问题是我似乎无法将多个对象写入 JSON 文件,因为我只得到一个 object:

    {
    "eventStatus": "Failure",
    "eventType": "Archive",
    "objectName": "Template",
    "time": "2022-08-21T16:09:31.863Z"
    }

How do I write a for loop so that all of the needed key values get written into the new JSON file?如何编写一个 for 循环,以便将所有需要的键值写入新的 JSON 文件?

It appears that new data cannot be updated in dictionary.似乎无法在字典中更新新数据。

So, The answer I came up with is json_data.update(dictionary) to add to the for loop.所以,我想出的答案是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)

I don't know if it will be solved because I can't check it, but I hope it helps you.我不知道它是否会解决,因为我无法检查它,但我希望它可以帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM