Learn to serialize a complex python class (e.g. User) and write serialized JSON data in file by extending JSONEncoder and custom serialization method.
In Python serialize complex object to JSON example, we have following User class. Here, birthdate of type datetime.
class User:
def __init__(self, id, name, birthdate):
self.id = id
self.name = name
self.birthdate = birthdate
If we don’t use the custom serialization, we will get the error : TypeError: Object of type User is not JSON serializable.
1. Python Custom Serialization using Serializer Method
1.1. Add default Serializer Method
Add a default serializer method to User class itself. This will be invoked by Python while dumping the JSON.
We can write the complete logic to convert the User object to python dictionary object here.
class User:
def __init__(self, id, name, birthdate):
self.id = id
self.name = name
self.birthdate = birthdate
def to_dict(u):
if isinstance(u, User):
dict = {
"id": u.id,
"name": u.name,
"birthdate": u.birthdate.strftime("%d %b %y")
}
return dict
else:
type_name = u.__class__.__name__
raise TypeError("Unexpected type {0}".format(type_name))
1.2. Use ‘default’ attribute on json.dumps()
Next, to use this serializer method, use the default attribute in json.dump() method. It will be automatically called by python while converting the complex object to JSON.
import json from user import User import datetime from UserEncoder import UserEncoder u = User(1, 'TestUser', datetime.datetime(1991, 1, 6)) # Convert User object to JSON print(json.dumps(u, default=User.to_dict))
Program output.
{"id": 1, "name": "TestUser", "birthdate": "06 Jan 91"}
2. Python Custom Serialization using JSONEncoder
Another way to add the similar complex object to JSON converter logic – is to extend the JSONEncoder class.
The following UserEncoder class overrides the default method of UserEncoder class and provides the logic to convert the complex class to JSON.
import json
import datetime
from user import User
class UserEncoder(json.JSONEncoder):
def default(self, u):
if isinstance(u, User):
dict = {
"id": u.id,
"name": u.name,
"birthdate": u.birthdate.strftime("%d %b %y")
}
return dict
else:
type_name = u.__class__.__name__
raise TypeError("Unexpected type {0}".format(type_name))
1.2. Use ‘cls’ attribute on json.dumps()
To use custom JSONEncoder, use the cls attribute in json.dump() method. It will be automatically called by python while converting the complex object to JSON.
import json from user import User import datetime from UserEncoder import UserEncoder u = User(1, 'TestUser', datetime.datetime(1991, 1, 6)) # Convert User object to JSON print(json.dumps(u, cls=UserEncoder))
Program output.
{"id": 1, "name": "TestUser", "birthdate": "06 Jan 91"}
Happy Learning !!
Comments