ItSolutionStuff.com

How to Convert Dictionary to JSON in Python?

By Hardik Savani • October 30, 2023
Python

Hey Dev,

Today, I will let you know example of python dictionary convert to json. In this article, we will implement a how to convert dict to json in python. If you have a question about how to convert dictionary to json file in python then I will give a simple example with a solution. If you have a question about how to convert dictionary to json string in python then I will give a simple example with a solution. follow the below step for how to convert dictionary to json in python.

There are several ways to convert python dictionary to json. we will use dumps() function of json library to convert dictionary to json string in python.

So, without further ado, let's see simple examples:

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

Example 1:

main.py

# Created New Dictionary
myDictionary = {
  "id": 1,
  "name": "Hardik Savani",
  "email": "hardik@gmail.com"
}
    
# Dictionary convert to json
jsonDictionary = json.dumps(myDictionary)
    
print(jsonDictionary)

Output:

'{"id": 1, "name": "Hardik Savani", "email": "hardik@gmail.com"}'

Example 2:

main.py

# Created New Dictionary
myDictionary = {
  "id": 1,
  "name": "Hardik Savani",
  "email": "hardik@gmail.com"
}
  
# Dictionary convert to json file
with open("demo.json", "w") as outfile:
    json.dump(myDictionary, outfile)
  
print("Created new demo.json file")

Output:

Created new demo.json file

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 Convert Dictionary Values into List in Python?

Read Now →

How to Convert Dictionary to List in Python?

Read Now →

How to Get Length of Dictionary Python?

Read Now →

Python Dictionary Remove Duplicate Values Example

Read Now →

Python Dictionary Check if Value is Empty Example

Read Now →

How to Check if Python Dictionary is Empty or Not?

Read Now →

Check if Key Value Pair Exists in Dictionary Python Example

Read Now →

Python Dictionary Check if Value Exists Example

Read Now →

Python Dictionary Check if Key Exists Example

Read Now →

How to Update Value in Python Dictionary?

Read Now →

How to Change Value in Python Dictionary?

Read Now →

Python Dictionary Remove Element by Value Example

Read Now →

Python Dictionary Delete Item by Key Example

Read Now →

How to Remove Item from Dictionary in Python?

Read Now →