How to Create a New JSON File in Python

In this tutorial, we’ll discuss how to create a new JSON (JavaScript Object Notation) file in Python. JSON 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 used to store information in an organized, easy-to-access manner. It gives us a readable collection of data that can be accessed in a logical manner.

Step 1: Install Required Python Library

All Python installations come with the built-in json module, so no extra installation is required. This module provides a way for Python to encode and decode the JSON data.

Step 2: Create a Python Dictionary

To create a JSON file in Python, we need to start with a dictionary that can contain key-value pairs. So, the first step is to create the Python Dictionary.

Step 3: Convert Python Dictionary to JSON

We use the json.dumps() function to convert the Python dictionary into a JSON string. Let’s convert the dictionary we created earlier:

Step 4: Write the JSON data to a file

Finally, we can write the JSON string to a file using the write() function. Here is how to do it:

Full Python Code

Output File

Here is our resulting JSON file:

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

Conclusion

And that’s it! You have successfully created a new JSON file in Python. The JSON file is easy for humans to read and for machines to parse and generate.

This can be particularly useful in various scenarios such as storing data, generating configuration files, and much more.

For more advanced manipulation of JSON files, the Python documentation provides a wealth of information and methods available in the json module.