function safe_json_serialize
Recursively converts Python objects into JSON-serializable formats, with special handling for datetime objects and objects with to_dict() methods.
/tf/active/vicechatdev/CDocs/utils/__init__.py
180 - 198
simple
Purpose
This function provides safe serialization of complex Python objects to JSON-compatible formats. It handles datetime objects by converting them to formatted strings, recursively processes dictionaries and lists, and supports custom objects that implement a to_dict() method. This is particularly useful when preparing data for JSON APIs, logging, or storage where standard json.dumps() would fail on non-serializable types.
Source Code
def safe_json_serialize(obj: Any) -> Any:
"""
Safely serialize object to JSON, handling datetime objects.
Args:
obj: Object to serialize
Returns:
JSON-serializable object
"""
if isinstance(obj, datetime):
return obj.strftime(DATETIME_FORMAT)
elif hasattr(obj, "to_dict") and callable(obj.to_dict):
return obj.to_dict()
elif isinstance(obj, dict):
return {k: safe_json_serialize(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [safe_json_serialize(item) for item in obj]
return obj
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
obj |
Any | - | positional_or_keyword |
Parameter Details
obj: Any Python object to be serialized. Can be a datetime object, a custom object with a to_dict() method, a dictionary, a list, or any primitive type. The function recursively processes nested structures.
Return Value
Type: Any
Returns a JSON-serializable version of the input object. Datetime objects are converted to strings using DATETIME_FORMAT constant. Objects with to_dict() methods are converted to dictionaries. Dictionaries and lists are recursively processed. Primitive types (str, int, float, bool, None) are returned unchanged. The return type matches the structure of the input but with all non-serializable types converted.
Dependencies
datetime
Required Imports
from datetime import datetime
from typing import Any
Usage Example
from datetime import datetime
from typing import Any
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
def safe_json_serialize(obj: Any) -> Any:
if isinstance(obj, datetime):
return obj.strftime(DATETIME_FORMAT)
elif hasattr(obj, "to_dict") and callable(obj.to_dict):
return obj.to_dict()
elif isinstance(obj, dict):
return {k: safe_json_serialize(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [safe_json_serialize(item) for item in obj]
return obj
# Example usage
import json
data = {
'timestamp': datetime.now(),
'values': [1, 2, datetime(2023, 1, 1)],
'nested': {'date': datetime(2023, 6, 15, 10, 30)}
}
serialized = safe_json_serialize(data)
json_string = json.dumps(serialized)
print(json_string)
Best Practices
- Ensure DATETIME_FORMAT constant is defined before using this function
- This function does not handle circular references - avoid passing objects with circular dependencies
- Custom objects should implement a to_dict() method for proper serialization
- The function returns the original object for types it doesn't recognize, which may still cause json.dumps() to fail - consider adding additional type handlers if needed
- For large nested structures, be aware of potential recursion depth limits
- Consider wrapping the final json.dumps() call in a try-except block to catch any remaining serialization errors
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function to_json 75.1% similar
-
function safe_json_dumps 69.0% similar
-
function clean_for_json_v12 61.6% similar
-
function clean_for_json_v3 61.3% similar
-
function clean_for_json_v10 61.0% similar