When you’re coding in Python, you often deal with JSON, its a format that is used to store and exchange data. If you’ve worked with APIs, you’ve likely parsed JSON responses before.
JSON is like a dictionary in Python, storing data as key-value pairs, making it easy to understand and work with. Python’s json module helps convert Python dictionaries to JSON strings and vice versa.
In this tutorial, our main focus is on converting python dictionaries to JSON using the json module. Let’s dive into the code!
Now, to convert a Python dictionary to JSON string, you can use the dumps() function from the json module. The dumps() function takes in a Python object and returns the JSON string representation. In practice, however, you’ll need to convert not a single dictionary but a collection such as a list of dictionaries.
Let us take an example.
In this example, we first import the json module. Then, we create a list of dictionaries called data. Next, we use the json.dumps() function to convert the data list into a JSON string. Finally, we print the JSON string to the console.
import json
# Sample list of dictionaries
data = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
# Convert list of dictionaries to JSON string
json_string = json.dumps(data)
# Print the JSON string
print(json_string)
Output:

Let us take another example:
assume, we have books, a list of dictionaries, where each dictionary holds information on a book. So each book record is in a Python dictionary with the following keys: title, author, publication_year, and genre.
import json
books = [
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"publication_year": 1925,
"genre": "Fiction"
},
{
"title": "To Kill a Mockingbird",
"author": "Harper Lee",
"publication_year": 1960,
"genre": "Fiction"
},
{
"title": "1984",
"author": "George Orwell",
"publication_year": 1949,
"genre": "Fiction"
}
]
# Convert dictionary to JSON string
json_string = json.dumps(books, indent=4)
print(json_string)
Output:

Explanation:
import json: This line imports thejsonmodule in Python, which provides functions for encoding and decoding JSON data.books = [...]: This defines a list calledbookscontaining three dictionaries. Each dictionary represents information about a book, including its title, author, publication year, and genre.json_string = json.dumps(books, indent=4): This line uses thejson.dumps()function to convert thebookslist into a JSON-formatted string. Theindent=4argument is used to format the JSON string with an indentation of 4 spaces, making it more readable.print(json_string): This line prints the JSON-formatted string to the console.
Nested Python Dictonarie
import json
books = [
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"publication_year": 1925,
"genre": "Fiction",
"reviews": [
{"user": "Alice", "rating": 4, "comment": "Captivating story"},
{"user": "Bob", "rating": 5, "comment": "Enjoyed it!"}
]
},
{
"title": "To Kill a Mockingbird",
"author": "Harper Lee",
"publication_year": 1960,
"genre": "Fiction",
"reviews": [
{"user": "Charlie", "rating": 5, "comment": "A great read!"},
{"user": "David", "rating": 4, "comment": "Engaging narrative"}
]
},
{
"title": "1984",
"author": "George Orwell",
"publication_year": 1949,
"genre": "Fiction",
"reviews": [
{"user": "Emma", "rating": 5, "comment": "Orwell pulls it off well!"},
{"user": "Frank", "rating": 4, "comment": "Dystopian masterpiece"}
]
}
]
# Convert dictionary to JSON string
json_string = json.dumps(books, indent=4)
print(json_string)
Output:

To demonstrate a potential error and its rectification, we can modify the books list to include a non-serializable object, such as a datetime object, which cannot be directly converted to JSON. Here’s an example:
import json
from datetime import datetime
# Define a list of dictionaries containing book information
books = [
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"publication_year": 1925,
"genre": "Fiction"
},
{
"title": "To Kill a Mockingbird",
"author": "Harper Lee",
"publication_year": datetime.now(), # Using datetime object
"genre": "Fiction"
},
{
"title": "1984",
"author": "George Orwell",
"publication_year": 1949,
"genre": "Fiction"
}
]
try:
# Convert dictionary to JSON string
json_string = json.dumps(books, indent=4)
print(json_string)
except TypeError as e:
print(f"Error: {e}")
print("Removing non-serializable objects...")
# Remove non-serializable objects (datetime objects) from the list
for book in books:
if isinstance(book["publication_year"], datetime):
book["publication_year"] = str(book["publication_year"])
# Try converting again
json_string = json.dumps(books, indent=4)
print(json_string)
the publication_year of the second book is set to a datetime object obtained using datetime.now(), which is not serializable to JSON. To rectify this, we catch the TypeError that occurs during conversion and convert the datetime object to a string before retrying the conversion.

Conclusion:
we learned how to convert a Python dictionary to JSON format. JSON is a popular data format used for storing and exchanging data between systems. Using the json module in Python, we can easily convert Python dictionaries to JSON strings. This can be useful when working with APIs or when saving data to files. By following the examples and explanations in this tutorial, beginners can gain a solid understanding of how to work with JSON in Python and use it in their projects.





Leave a Reply