Convert a dictionary to JSON in Python
In this post, we will see how to convert a Python dictionary into JSON.
What is JSON?
JSON stands for Javascript object notation, which is used to store and transfer data.
json.dumps()
This is the method used to convert a dictionary into JSON.
Syntax
json.dumps(dictionary, indent)
Where,
dictionary is the input dictionary
indent is the units of indentation to be maintained
Example
Consider we have a dictionary,
data = {
"roll" : 1,
"name" : "mani",
"branch" : "CSE"
}
To convert it to JSON, we need to use the built-in json method.
import json
data = {
"roll" : 1,
"name" : "mani",
"branch" : "CSE"
}
data_json = json.dumps( data, indent = 4)
print(data_json)