How to Write JSON Data to a File in Python?

As a developer working on a project for a US-based client, I recently encountered a situation where I needed to save JSON data to a file for later use. After researching and implementing the solution, I want to share the process. In this tutorial, I will explain how to write JSON data to a file in Python.

JSON in Python

JSON (JavaScript Object Notation) is a simple data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It consists of key-value pairs and arrays, making it a popular choice for data serialization and configuration files.

Read How to Close a File in Python?

Write JSON Data to a File in Python

To write JSON data to a file in Python, we can use the built-in json module. The json module provides a convenient method called json.dump() that allows us to serialize JSON data and write it to a file. Here’s how you can do it:

  1. Import the json module:
import json
  1. Prepare your JSON data. For example, let’s create a dictionary representing a user’s profile:
user_profile = {
    "name": "John Doe",
    "age": 35,
    "city": "New York",
    "country": "USA",
    "email": "johndoe@example.com"
}
  1. Open a file in write mode using Python’s open() function and specify the file path:
with open("user_profile.json", "w") as file:
    # Write JSON data to the file
    json.dump(user_profile, file)

In this example, we open a file named “user_profile.json” in write mode using the with statement. The with statement ensures that the file is properly closed after writing the data, even if an exception occurs.

  1. Use json.dump() to serialize the JSON data and write it to the file. The first argument is the JSON data (in this case, the user_profile dictionary), and the second argument is the file object (file).

Output:

{'name': 'John Doe', 'age': 35, 'city': 'New York', 'country': 'USA', 'email': 'johndoe@example.com'}

I executed the above example code and added the screenshot below.

Write JSON Data to a File in Python

Check out How to Save Variables to a File in Python?

Read JSON Data from a File

Now that you know how to write JSON data to a file, let’s briefly cover how to read JSON data from a file:

  1. Open the file in read mode using open():
import json

# Open the file in read mode
with open("user_profile.json", "r") as file:
    # Read JSON data from the file
    user_data = json.load(file)

# Print the loaded JSON data
print(user_data)
  1. Use json.load() to parse the JSON data from the file and store it in a variable (user_data).

Output:

{'name': 'John Doe', 'age': 35, 'city': 'New York', 'country': 'USA', 'email': 'johndoe@example.com'}

I executed the above example code and added the screenshot below.

How to Write JSON Data to a File in Python

Read How to Read a Specific Line from a Text File in Python?

Handle Exceptions

When working with files and JSON data, it’s important to handle exceptions gracefully. You can use a try-except block to catch and handle potential exceptions:

try:
    with open("user_profile.json", "w") as file:
        json.dump(user_profile, file)
except IOError as e:
    print(f"An error occurred while writing to the file: {e}")
except ValueError as e:
    print(f"Invalid JSON data: {e}")

This code attempts to write the JSON data to the file, but if an IOError occurs (e.g., insufficient permissions, disk full), it catches the exception and prints an error message. Similarly, if the JSON data is invalid and causes a ValueError , it catches the exception and prints an appropriate message.

Check out How to Read the Last Line of a File in Python?

Conclusion

In this article, I explained how to write JSON data to a file in Python. I discussed how to write JSON data to a file in Python and read JSON data from a file. I also covered the concept of handling exceptions.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.