Picture by Creator
When constructing purposes in Python, JSON is without doubt one of the frequent knowledge codecs you’ll work with. And in case you’ve ever labored with APIs, you are most likely already conversant in parsing JSON responses from APIs.
As you understand, JSON is a text-based format for knowledge interchange, which shops knowledge in key-value pairs and is human readable. And Python dictionaries retailer knowledge in key-value pairs. Which makes it intuitive to load JSON strings into dictionaries for processing and in addition dump knowledge from dictionaries into the JSON strings.
On this tutorial, we’ll learn to convert a Python dictionary to JSON utilizing the built-in json module. So let’s begin coding!
To transform a Python dictionary to JSON string, you need to use the dumps()
perform from the json module. The dumps()
perform takes in a Python object and returns the JSON string illustration. In observe, nevertheless, you’ll have to convert not a single dictionary however a group similar to an inventory of dictionaries.
So let’s select such an instance. Say we now have books
, an inventory of dictionaries, the place every dictionary holds info on a e-book. So every e-book report is in a Python dictionary with the next keys: title, writer, publication_year, and style.
When calling json.dumps()
, we set the non-obligatory indent
parameter—the indentation within the JSON string because it helps enhance readability (sure, fairly printing json we’re ??):
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)
If you run the above code, it is best to get an analogous output:
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"
}
]
Subsequent, let’s take an inventory of nested Python dictionaries and acquire the JSON illustration of it. Let’s lengthen the books
dictionary by including a “reviews” key. Whose worth is an inventory of dictionaries with every dictionary containing info on a overview, particularly, “user”, “rating”, and “comment”.
So we modify the books
dictionary like so:
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)
Be aware that we use the identical indent worth of 4, and working the script offers the next 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"
}
]
}
]
The dumps
perform has a number of non-obligatory parameters. We’ve already used one such non-obligatory parameter indent
. One other helpful parameter is sort_keys
. That is particularly useful when it’s essential to kind the keys of the Python dictionary when changing it to JSON
As a result of sort_keys
is ready to False
by default, so you’ll be able to set it to True
if it’s essential to kind the keys when changing to JSON.
Right here’s a easy particular person
dictionary:
import json
particular person = {
"name": "John Doe",
"age": 30,
"email": "john@example.com",
"address": {
"city": "New York",
"zipcode": "10001",
"street": "123 Main Street"
}
}
# Convert dictionary to a JSON string with sorted keys
json_string = json.dumps(particular person, sort_keys=True, indent=4)
print(json_string)
As seen, the keys are sorted in alphabetical order:
Output >>>
{
"address": {
"city": "New York",
"street": "123 Main Street",
"zipcode": "10001"
},
"age": 30,
"email": "john@example.com",
"name": "John Doe"
}
Within the examples we’ve coded up to now, the keys and values of the dictionary are all JSON serializable. The values have been all strings or integers to be particular. However this may occasionally not all the time be the case. Some frequent non-serializable knowledge sorts embody datetime
, Decimal
, and set
.
No worries, although. You possibly can deal with such non-serializable knowledge sorts by defining customized serialization features for these knowledge sorts. After which setting the default
parameter of json.dumps()
to the customized features you outline.
These customized serialization features ought to convert the non-serializable knowledge right into a JSON-serializable format (who would’ve guessed!).
Right here’s a easy knowledge
dictionary:
import json
from datetime import datetime
knowledge = {
"event": "Meeting",
"date": datetime.now()
}
# Strive changing dictionary to JSON
json_string = json.dumps(knowledge, indent=2)
print(json_string)
We’ve used json.dumps()
as earlier than, so we’ll run into the next TypeError exception:
Traceback (most up-to-date name final):
File "/home/balapriya/djson/main.py", line 10, in
json_string = json.dumps(knowledge, 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
elevate TypeError(f'Object of sort {o.__class__.__name__} '
TypeError: Object of sort datetime will not be JSON serializable
The related a part of the error is: Object of sort datetime will not be JSON serializable. Okay, now let’s do the next:
- Outline a
serialize_datetime
perform that convertsdatetime
objects to ISO 8601 format utilizing theisoformat()
technique. - When calling
json.dumps()
, we set thedefault
parameter to theserialize_datetime
perform.
So the code appears as follows:
import json
from datetime import datetime
# Outline a customized serialization perform for datetime objects
def serialize_datetime(obj):
if isinstance(obj, datetime):
return obj.isoformat()
knowledge = {
"event": "Meeting",
"date": datetime.now()
}
# Convert dictionary to JSON
# with customized serialization for datetime
json_string = json.dumps(knowledge, default=serialize_datetime, indent=2)
print(json_string)
And right here’s the output:
Output >>>
{
"event": "Meeting",
"date": "2024-03-19T08:34:18.805971"
}
And there you’ve got it!
To recap: we went over changing a Python dictionary to JSON, and utilizing the indent
and sort_keys
parameters as wanted. We additionally discovered tips on how to deal with JSON serialization errors.
You will discover the code examples on GitHub. I’ll see you all in one other tutorial. Till then, hold coding!
Bala Priya C is a developer and technical author from India. She likes working on the intersection of math, programming, knowledge science, and content material creation. Her areas of curiosity and experience embody DevOps, knowledge science, and pure language processing. She enjoys studying, writing, coding, and low! At present, she’s engaged on studying and sharing her data with the developer neighborhood by authoring tutorials, how-to guides, opinion items, and extra. Bala additionally creates partaking useful resource overviews and coding tutorials.