How to Convert Dictionary to JSON in Python?

By Hardik Savani October 30, 2023 Category : 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 :
Shares