16-Feb-2023
.
Admin
Hi Dev,
This article is focused on convert dictionary to json in python tutorial example. you can understand a concept of how to convert dictionary to json in python. Here you will learn how to convert dictionary to json string in python. This post will give you simple example of how to convert dictionary to json file in python. Alright, let’s dive into the steps.
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.
Example 1:
main.py
# Created New Dictionary
myDictionary = {
"id": 1,
"name": "Piyush Kamani",
"email": "piyush@gmail.com"
}
# Dictionary convert to json
jsonDictionary = json.dumps(myDictionary)
print(jsonDictionary)
Output:
'{"id": 1, "name": "Piyush Kamani", "email": "piyush@gmail.com"}'
Example 2:
main.py
# Created New Dictionary
myDictionary = {
"id": 1,
"name": "Piyush Kamani",
"email": "piyush@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
#Python