Python Write a JSON File Tutorial

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


Hi Dev,

This article is focused on python write data in json file. This article will give you simple example of json dump python example. you can see how to write json file in python. this example will help you how to write data to json file in python.

So, if you want to write json file in python then i would like to describe python has json library to generate JSON file using python script. we will use open() and json dump() function to write json file.

So let's see bellow example:

Example

First of all we need to create data.json file.

data.json
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")

After running example successfully, you will see a data.json file saved in your root path, with the following content:

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....