write to a json file in python

To write to a JSON file in Python, you can follow these steps:

  1. Create the data you want to write to the JSON file. This can be a dictionary or a list of dictionaries.
  2. Use the open() function to open a file in write mode. When opening the file, you can specify the name of the file and the file mode (w for write mode).
  3. Use the json.dump() function to write the data to the file. This function takes two arguments: the data you want to write and the file object you want to write it to.
  4. Close the file using the close() method on the file object.

Here's an example code snippet:

main.py
import json

data = {'name': 'John', 'age': 30, 'city': 'New York'}

with open('data.json', 'w') as f:
    json.dump(data, f)
126 chars
7 lines

In this example, we create a dictionary called data with some key-value pairs. We then open a file called data.json in write mode using a context manager (with statement), and write the data to the file using the json.dump() function. Finally, we close the file.

This will create a file called data.json in the current working directory (where your Python script is located) with the following contents:

{"name": "John", "age": 30, "city": "New York"}
48 chars
2 lines

Note that the json.dump() function automatically converts the dictionary to a JSON string and writes it to the file. If you have a list of dictionaries, you can pass the list to the json.dump() function instead of a single dictionary.

gistlibby LogSnag