How to Create JSON File in Python

0
19749
How to Create JSON File in Python

JSON has become the de facto standard to exchange data between client and server. Python has an inbuilt package called json for encoding and decoding JSON data. To read and write the json data, we have to use the json package. For file handling, Python provides many functions that will do the job.

How to create a JSON file in Python

To create a json file in Python, use with open() function. The open() function takes the file name and mode as an argument. If the file is not there, then it will be created.

Python With Statement is used to open files. The with statement is recommended for working with files because it assures that open file descriptors are closed automatically after program execution leaves the context of the with statement.

# app.py

import json

with open('new_file.json', 'w') as f:
    print("The json file is created")

In this code, we are trying to open a file called new_file.json with mode. However, the file does not exist in the file system, creating a new file in the same folder.

Create a json file from the existing json file in Python

To create a json file from an existing json file, open the existing file in read mode and read the content of that file and use the open() and with statement in write mode and dump the json data to a new json file.

Let’s say we have the data.json existing file.

{
  "data": [
    {
      "color": "red",
      "value": "#f00"
    },
    {
      "color": "green",
      "value": "#0f0"
    },
    {
      "color": "blue",
      "value": "#00f"
    },
    {
      "color": "black",
      "value": "#000"
    }
  ]
}

Now, we will create a new json file from this data.json file.

# app.py

import json

with open('data.json') as f:
    data = json.load(f)

with open('new_file.json', 'w') as f:
    json.dump(data, f, indent=2)
    print("New json file is created from data.json file")

Output

python3 app.py
New json file is created from data.json file

So basically, we are reading the existing json file and creating a new json file, and dump the content to this new file.

Conclusion

Using Python’s context manager, you can create a json file and open it in write mode. JSON files conveniently end in a .json extension.

To work with json files in Python:

  1. Import the json package.
  2. To read the data, use the load() or loads() function.
  3. Then you process the data.
  4. To alter the data, use the dump() or dumps() function.

This is not always the case, but you will probably follow these steps.

That is it for creating a json file in Python.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.