🔍 Code Extractor

function safe_json_serialize

Maturity: 51

Recursively converts Python objects into JSON-serializable formats, with special handling for datetime objects and objects with to_dict() methods.

File:
/tf/active/vicechatdev/CDocs/utils/__init__.py
Lines:
180 - 198
Complexity:
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

    Converts a Python object to a formatted JSON string with 2-space indentation, using a safe serialization helper function.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function safe_json_dumps 69.0% similar

    Safely serializes Python objects to JSON format, handling NaN values and datetime objects that would otherwise cause serialization errors.

    From: /tf/active/vicechatdev/full_smartstat/services.py
  • function clean_for_json_v12 61.6% similar

    Recursively sanitizes Python objects to make them JSON-serializable by converting non-serializable types (NumPy types, pandas objects, tuples, NaN/Inf values) into JSON-compatible formats.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/290a39ea-3ae0-4301-8e2f-9d5c3bf80e6e/project_3/analysis.py
  • function clean_for_json_v3 61.3% similar

    Recursively converts Python objects (including NumPy and Pandas types) into JSON-serializable formats by handling special numeric types, NaN/Inf values, and nested data structures.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/f0a78968-1d2b-4fbe-a0c6-a372da2ce2a4/project_1/analysis.py
  • function clean_for_json_v10 61.0% similar

    Recursively converts Python objects containing NumPy and Pandas data types into JSON-serializable native Python types.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/c385e1f5-fbf6-4832-8fd4-78ef8b72fc53/project_1/analysis.py
← Back to Browse