Write a JSON File in Python Tutorial Example

03-Jan-2023

.

Admin

Write a JSON File in Python Tutorial Example

Hi Dev,

This post will give you example of write a json file in python tutorial example. you'll learn how to write string to json file in python. this example will help you how to write data to json file in python. it's simple example of json dump python example. you will do the following things for python write json file example.

If you want to write a JSON file from the list in python, then I would like to help you step by step on how to write JSON file in python. python has json library to generate JSON file using python script. we will use open() and json dump() function to write json file.

Example :


main.py

import json

# Create List for write data into json file

data = [

{ "ID": 1, "Name": "Piyush Patel", "email": "piyush@gmail.com"},

{ "ID": 2, "Name": "Savan Rathod", "email": "savan@gmail.com"},

{ "ID": 3, "Name": "Jaydip Pathar", "email": "jaydip@gmail.com"}

]

# 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": "Piyush Patel",

"email": "piyush@gmail.com"

},

{

"ID": 2,

"Name": "Savan Rathod",

"email": "savan@gmail.com"

},

{

"ID": 3,

"Name": "Jaydip Pathar",

"email": "jaydip@gmail.com"

}

]

#Python