How to Convert Dictionary to JSON in Python
To convert a dictionary to JSON in Python, you can use the json.dumps() function from the json module.
The following example shows how to convert a dictionary to JSON using the json.dumps() function in Python.
Using json.dumps() Function
We can use the json.dumps() function to convert a dictionary to JSON.
Suppose we have the following dictionary:
import json
# Declare dictionary
dict1 = {1: "Mon", 2: "Tue", 3: "Wed"}
# Convert dictionary to JSON using dumps() function
json_ = json.dumps(dict1)
# Show JSON data
print("JSON data:", json_)
Output: 👇️
JSON data: {"1": "Mon", "2": "Tue", "3": "Wed"}
In this example, we use the json.dumps() function to convert the dictionary dict1 to a JSON string json_. The output shows the JSON data converted from the dictionary using the json.dumps() function.
Conclusion
We can use the json.dumps() function from the json module to convert a dictionary to JSON in Python. This method provides a convenient way to serialize a dictionary into a JSON string.