简体   繁体   中英

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:

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:

    {
    "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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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