ItSolutionStuff.com

How to Write a JSON File in Python?

By Hardik Savani • October 30, 2023
Python

Hey Guys,

I am going to explain to you example of how to write json file in python. I would like to show you python write data in json file. If you have a question about python write json file example then I will give a simple example with a solution. I explained simply about json dump python example. Alright, let us dive into the details.

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.

So, let's see a simple example with output:

You can use these examples with python3 (Python 3) version.

Example 1:

main.py

import json
  
# Create List for write data into json file
data = [
    { "ID": 1, "Name": "Hardik Savani", "email": "hardik@gmail.com"},
    { "ID": 2, "Name": "Vimal Kashiyani", "email": "vimal@gmail.com"},
    { "ID": 3, "Name": "Harshad Pathak", "email": "harshad@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:

After run successfully above example, you will see data.json file saved in your root path and file content will be as the below:

[
  {
    "ID": 1,
    "Name": "Hardik Savani",
    "email": "hardik@gmail.com"
  },
  {
    "ID": 2,
    "Name": "Vimal Kashiyani",
    "email": "vimal@gmail.com"
  },
  {
    "ID": 3,
    "Name": "Harshad Pathak",
    "email": "harshad@gmail.com"
  }
]

I hope it can help you...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Create a JSON File in Python?

Read Now →

Python Read CSV File Specific Column Example

Read Now →

Python Read CSV File Line by Line Example

Read Now →

How to Read a CSV File in Python?

Read Now →

How to Write CSV File in Python?

Read Now →

How to Write Multiple Rows in CSV using Python?

Read Now →

Python Write CSV File from List Example

Read Now →

How to Read a Text File in Python?

Read Now →

How to Create Text File in Python?

Read Now →

Python Convert List into String with Commas Example

Read Now →

How to Get Unique Elements from List in Python?

Read Now →

Python Get File Extension from Filename Example

Read Now →

Python Create Zip Archive from Directory Example

Read Now →