LearnPython has the Biggest Discount Ever! ------ Get $349 $129 Lifetime Access to all 13 Python Courses
How to Convert Dict to JSON in Python
To convert a dictionary to JSON in Python, you can use the built-in json
module. Simply call json.dumps()
function with the dictionary as the parameter.
import json
# Create a Python dictionary
my_dict = {
"name": "John",
"age": 30,
"city": "New York"
}
# Convert the dictionary to JSON
json_data = json.dumps(my_dict)
# Print the JSON string
print(json_data)
Output:
{"name": "John", "age": 30, "city": "New York"}
In this example:
- We import the
json
module. - We create a Python dictionary called
my_dict
with some key-value pairs. - We use the
json.dumps()
function to convert the dictionary to a JSON string. Thedumps()
function serializes the dictionary into a JSON-formatted string. - We print the resulting JSON string.
The json.dumps()
function takes the dictionary as input and returns the corresponding JSON representation as a string.
You can also customize the JSON output by using additional parameters of json.dumps()
. For example:
indent
: Specifies the indentation level for pretty-printing the JSON string.sort_keys
: If set toTrue
, the keys in the JSON output will be sorted alphabetically.separators
: Allows you to specify custom separators for the JSON string.
Here’s an example with some additional parameters:
json_data = json.dumps(my_dict, indent=4, sort_keys=True)
print(json_data)
Output:
{
"age": 30,
"city": "New York",
"name": "John"
}
In this case, the JSON string is pretty printed with an indentation level of 4 spaces, and the keys are sorted alphabetically.
Converting a dictionary to JSON is useful when you need to transmit data between different systems or when you want to store structured data in a portable format.