Image by author
When building applications in Python, JSON is one of the common data formats you will work with. And if you've ever worked with APIs, you're probably already familiar with parsing API JSON responses.
As you know, JSON is a text-based format for data exchange, which stores data in key-value pairs and is human readable. And Python dictionaries store data in key-value pairs. Which makes it intuitive to load JSON strings into dictionaries for processing and also dump data from dictionaries into JSON strings.
In this tutorial, we will learn how to convert a Python dictionary to JSON using the built-in json module. So let's start coding!
To convert a Python dictionary to a JSON string, you can use the dumps()
function from the json module. He dumps()
The function takes a Python object and returns the JSON string representation. In practice, however, you will need to convert not a single dictionary but a collection, such as a list of dictionaries.
So let's choose an example like that. say that we have books
, a list of dictionaries, where each dictionary contains information about a book. So each book record is in a Python dictionary with the following keys: title, author, publication_year, and genre.
when calling json.dumps()
we configure the optional indent
parameter: the indentation in the JSON string, as it helps improve readability (yeah, are we pretty much printing json?):
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)
When you run the code above, you should get a similar result:
Output >>>
(
{
"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"
}
)
Next, let's take a list of nested Python dictionaries and get their JSON representation. Let's extend the books
dictionary by adding a “reviews” key. Whose value is a list of dictionaries and each dictionary contains information about a review, i.e. “user”, “rating” and “comment”.
Then we modify the books
dictionary like this:
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)
Note that we use the same indentation value of 4 and running the script gives the following output:
Output >>>
(
{
"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"
}
)
}
)
He dumps
The function has several optional parameters. We have already used one of those optional parameters. indent
. Another useful parameter is sort_keys
. This is especially useful when you need to sort Python dictionary keys when converting to JSON.
Because sort_keys
is set to False
by default, so you can set it to True
if you need to sort the keys when converting to JSON.
Here is a simple person
dictionary:
import json
person = {
"name": "John Doe",
"age": 30,
"email": "[email protected]",
"address": {
"city": "New York",
"zipcode": "10001",
"street": "123 Main Street"
}
}
# Convert dictionary to a JSON string with sorted keys
json_string = json.dumps(person, sort_keys=True, indent=4)
print(json_string)
As you can see, the keys are arranged alphabetically:
Output >>>
{
"address": {
"city": "New York",
"street": "123 Main Street",
"zipcode": "10001"
},
"age": 30,
"email": "[email protected]",
"name": "John Doe"
}
In the examples we've coded so far, the dictionary keys and values are all serializable to JSON. All values were strings or integers to be specific. But this may not always be the case. Some common non-serializable data types include datetime
, Decimal
and set
.
But do not worry. You can handle these non-serializable data types by defining custom serialization functions for those data types. And then setting the default
parameter json.dumps()
to custom functions that you define.
These custom serialization functions should convert non-serializable data to a JSON serializable format (who would have guessed!).
Here is a simple data
dictionary:
import json
from datetime import datetime
data = {
"event": "Meeting",
"date": datetime.now()
}
# Try converting dictionary to JSON
json_string = json.dumps(data, indent=2)
print(json_string)
we have used json.dumps()
As before, we will encounter the following TypeError exception:
Traceback (most recent call last):
File "/home/balapriya/djson/main.py", line 10, in
json_string = json.dumps(data, indent=2)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/__init__.py", line 238, in dumps
**kw).encode(obj)
^^^^^^^^^^^
...
File "/usr/lib/python3.11/json/encoder.py", line 180, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type datetime is not JSON serializable
The relevant part of the error is: The object of type datetime is not serializable in JSON. Ok, now let's do the following:
- Define a
serialize_datetime
function that convertsdatetime
objects to ISO 8601 format using theisoformat()
method. - when calling
json.dumps()
we configure thedefault
parameter toserialize_datetime
function.
So the code looks like this:
import json
from datetime import datetime
# Define a custom serialization function for datetime objects
def serialize_datetime(obj):
if isinstance(obj, datetime):
return obj.isoformat()
data = {
"event": "Meeting",
"date": datetime.now()
}
# Convert dictionary to JSON
# with custom serialization for datetime
json_string = json.dumps(data, default=serialize_datetime, indent=2)
print(json_string)
And here is the result:
Output >>>
{
"event": "Meeting",
"date": "2024-03-19T08:34:18.805971"
}
And there you have it!
In summary: we go over converting a Python dictionary to JSON and using the indent
and sort_keys
parameters as necessary. We also learned how to handle JSON serialization errors.
You can find the code examples. on GitHub. I'll see you all in another tutorial. Until then, keep coding!
twitter.com/balawc27″ rel=”noopener”>Bala Priya C. is a developer and technical writer from India. He enjoys working at the intersection of mathematics, programming, data science, and content creation. His areas of interest and expertise include DevOps, data science, and natural language processing. He likes to read, write, code and drink coffee! Currently, he is working to learn and share his knowledge with the developer community by creating tutorials, how-to guides, opinion pieces, and more. Bala also creates engaging resource descriptions and coding tutorials.
<script async src="//platform.twitter.com/widgets.js” charset=”utf-8″>