How to Create a JSON File in Python

To create a json file in Python, you can use the “with open()” expression. The “open()” function takes the file name and mode as an argument. If the file doesn’t exist, it will be created. 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.

import json

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

Creating a json file from the existing json file in Python

To create a json file from an existing json file in Python, you can use the “open()” and with statement in write mode and dump the json data into a new json 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.

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

New json file is created from data.json file

That’s it.

Leave a Comment

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