Custom JSON Encoding
Lesson 6 of 9 in Coddy's Python JSON course.
Custom JSON encoding is a powerful feature in Python's json module that allows you to serialize complex Python objects that are not natively supported by JSON. This is particularly useful when working with custom classes or objects that don't have a direct JSON representation.
The JSONEncoder Class
To create a custom JSON encoder, you need to subclass the json.JSONEncoder class and override its default() method:
import json
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, YourCustomClass):
return obj.to_dict() # Convert your object to a dictionary
return json.JSONEncoder.default(self, obj)
Using the Custom Encoder
Once you've defined your custom encoder, you can use it with json.dumps() or json.dump():
json_string = json.dumps(your_object, cls=CustomEncoder)
Example: Encoding a Custom Class
Let's look at a practical example:
import json
from datetime import datetime
class Person:
def __init__(self, name, birthdate):
self.name = name
self.birthdate = birthdate
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Person):
return {"name": obj.name, "birthdate": obj.birthdate.isoformat()}
elif isinstance(obj, datetime):
return obj.isoformat()
return json.JSONEncoder.default(self, obj)
person = Person("Alice", datetime(1990, 5, 15))
json_string = json.dumps(person, cls=CustomEncoder, indent=2)
print(json_string)
This example demonstrates how to encode a custom Person class and handle the datetime object within it.
Key Points
- The
default()method is called for objects that aren't natively serializable. - Always provide a way to fall back to the default encoder for unknown types.
- Custom encoders are useful for handling complex data structures, custom classes, and non-standard Python types.
By using custom JSON encoders, you can seamlessly integrate your complex Python objects into JSON workflows, making data serialization more flexible and powerful.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a custom JSON encoder for a ComplexNumber class. The encoder should convert complex numbers to a JSON object with 'real' and 'imag' keys for the real and imaginary parts, respectively.
- Define a
ComplexNumberclass withrealandimagattributes. - Create a custom
JSONEncodersubclass that handlesComplexNumberobjects. - Implement a function that takes a list of
ComplexNumberobjects and returns a JSON string representation using the custom encoder.
The following input will be provided:
3.14,2.71
1.41,-1.73
2.0,0
0,-1
Each line represents a complex number with real and imaginary parts separated by a comma.
Print the resulting JSON string. Ensure that the JSON is formatted with an indent of 2 spaces.
Try it yourself
import json
# Read input
complex_numbers = []
while True:
try:
line = input().strip()
if line:
real, imag = map(float, line.split(','))
complex_numbers.append((real, imag))
except EOFError:
break
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
# TODO: Create a custom JSONEncoder subclass that handles ComplexNumber objects
# TODO: Implement a function that takes a list of ComplexNumber objects and returns a JSON string
# TODO: Convert the input data to ComplexNumber objects and use your function to create the JSON string
# Print the resulting JSON string
print(json_string)