Python Python Trim String Example

How to Convert Dictionary to JSON in Python


In this article, you will learn how to convert a dictionary to JSON in Python.

Let’s say you have a dictionary named ‘a’.

# Import JSON module
import json   
       
# A dictionary named 'a'  
a = {   
  "Name": "Meat Pizza",   
  "Price": "$12",  
  "Size": "Regular",
  "Crust Type": "Deep Dish"
}  

Convert Dictionary to JSON in Python

In order to convert a dictionary to JSON, you can use the json.dumps() method.

# Import JSON module
import json   
       
# A dictionary named 'a'  
a = {   
  "Name": "Meat Pizza",   
  "Price": "$12",  
  "Size": "Regular",
  "Crust Type": "Deep Dish"
}   
       
# Convert dictionary named 'a' to JSON  
print(json.dumps(a, indent = 4)) 
# {
#     "Name": "Meat Pizza",
#    "Price": "$12",
#    "Size": "Regular",
#    "Crust Type": "Deep Dish"
# }

Note: The json.dumps() method functions by converting Python objects to JSON string.


Share on social media

//