How to write JSON data to a file with Python?

Estimated read time 2 min read

To write JSON data to a file with Python, you can use the json module, which provides functions for working with JSON data. Here’s an example of how you can write JSON data to a file:

import json

data = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"

# Open the file in write mode
with open("data.json", "w") as file:
    # Write the JSON data to the file
    json.dump(data, file)

In this example, we have a dictionary data containing some JSON data. We open a file called “data.json” in write mode using the open() function and the "w" parameter. Then, we use the json.dump() function to write the JSON data from the data dictionary to the file.

The json.dump() function takes two arguments: the data to be written (in this case, the data dictionary) and the file object (in this case, the opened file). It converts the data to a JSON string representation and writes it to the file.

After executing this code, the “data.json” file will be created (or overwritten if it already exists) in the current directory, and it will contain the JSON data from the data dictionary.

Remember to handle any exceptions that may occur during file operations and ensure proper error handling in your code.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply