Python Create a JSON File Tutorial

Published On: 12/01/2023 | Category: Python


Hi Dev,

This article is focused on how to generate json file in python. you will learn how to save json file in python. I’m going to show you about how to create json file in python. I explained simply about how to write data to json file in python. Here, Creating a basic example of how to write string to json file in python.

Python scripts can create JSON files thanks to its json library. To create a json file, we'll use the open() and json dump() functions.

So let's see bellow example:

Example

main.py
import json
  
# Create List for write data into json file
data = [
    { "ID": 1, "Name": "Bhavesh Sonagra", "email": "[email protected]"},
    { "ID": 2, "Name": "Nikhil Patel", "email": "[email protected]"},
    { "ID": 3, "Name": "Piyush Kamani", "email": "[email protected]"}
]
  
# Create Json file with list
with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)
  
print("New data.json file is created from list")
Output
[
  {
    "ID": 1,
    "Name": "Bhavesh Sonagra",
    "email": "[email protected]"
  },
  {
    "ID": 2,
    "Name": "Nikhil Patel",
    "email": "[email protected]"
  },
  {
    "ID": 3,
    "Name": "Piyush Kamani",
    "email": "[email protected]"
  }
]

It will help you....