How To Save A JSON File In Python

In this tutorial, we will learn how to save a JSON file in Python. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate.

It is a very popular format for exchanging data, especially in web applications. Python provides a built-in library called json that allows us to work with JSON data.

Let’s explore how to save JSON data to a file using Python.

Step 1: Import the json library

First, we need to import the json library in our Python script.

Step 2: Create JSON data

Next, we will create an example JSON data that we will save to a file. We will use a dictionary to represent the JSON data, which will later be converted to a JSON string using the json.dump() method.

Step 3: Save JSON data to a file

Now that we have our JSON data ready, we can save it to a file. We will use Python’s built-in open() function to open a file in write mode (with ‘w’ as the second argument). Then, we will use the json.dump() function to write the JSON data into the file.

In the code above, the with statement is used to open and close the file properly once the operation is completed. The json.dump() function takes two arguments: the JSON data and the file object.

Full Code

Here’s the full code for saving JSON data to a file in Python:

Output

After running the code, you will see a new file named data.json created in the same directory as your Python script. This file will contain the following JSON data:

{
    "name": "John",
    "age": 30,
    "city": "New York"
}

Conclusion

In this tutorial, we learned how to save JSON data to a file in Python using the built-in json library. With the json.dump() function, we can easily write JSON data to files, making it convenient to store and share data in a widely supported format.