Intermediate LevelPython
How do you serialize custom classes, datetime objects, and UUIDs to JSON by subclassing json.JSONEncoder?
❓ Interview Prompt: Explain `json.dumps()`, `json.loads()`, `json.JSONEncoder`, handling non-serializable objects (`TypeError`), and custom encoders.
Python's native 'json' module supports basic types (dicts, lists, strings, numbers). Complex objects like 'datetime', 'UUID', or custom classes trigger 'TypeError: Object of type X is not JSON serializable'!
Custom Encoder Solution:
Subclass 'json.JSONEncoder' and override the 'default(self, obj)' method to convert custom objects into serializable types.
Code Implementation Example
python
import json
from datetime import datetime
from uuid import UUID, uuid4
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, UUID):
return str(obj)
return super().default(obj)
payload = {'id': uuid4(), 'timestamp': datetime.now()}
json_str = json.dumps(payload, cls=CustomJSONEncoder)
print(json_str)💡Serializing datetime and UUID objects using custom JSONEncoder.
🎯 Interview Key Takeaway
Subclass json.JSONEncoder to handle custom object serialization cleanly.
#json#JSONEncoder#Serialization#Intermediate
Back to all Python Questions→