append to a json file in python

To append data to a JSON file in Python, you'll first need to read the existing JSON data from the file, then add your new data to it, and finally overwrite the file with the updated JSON data.

Here's an example code snippet that demonstrates how to append a dictionary to a JSON file:

main.py
import json

# open file for reading
with open('data.json', 'r') as f:
    data = json.load(f)

# add new data as dictionary
new_data = {"name": "John", "age": 30, "city": "New York"}
data.append(new_data)

# open file for writing
with open('data.json', 'w') as f:
    json.dump(data, f)
288 chars
14 lines

In this code, we first open the JSON file for reading using json.load to convert the file content into a Python list of dictionaries. We then add our new dictionary to the list, and finally overwrite the file using json.dump to write the updated content back to the file.

Note that if you want to append multiple dictionaries to a JSON file, you can repeat the above code within a loop, adding each dictionary to the list before the final write operation.

gistlibby LogSnag