🔍 Code Extractor

function to_json

Maturity: 50

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

File:
/tf/active/vicechatdev/CDocs/utils/__init__.py
Lines:
200 - 210
Complexity:
simple

Purpose

This function provides a safe way to convert Python objects to JSON strings, handling objects that may not be directly JSON-serializable through the safe_json_serialize helper. It's useful for logging, API responses, data export, and debugging where human-readable JSON output is needed. The 2-space indentation makes the output more readable for display or file storage.

Source Code

def to_json(obj: Any) -> str:
    """
    Convert object to JSON string.
    
    Args:
        obj: Object to convert
        
    Returns:
        JSON string
    """
    return json.dumps(safe_json_serialize(obj), indent=2)

Parameters

Name Type Default Kind
obj Any - positional_or_keyword

Parameter Details

obj: Any Python object to be converted to JSON. Can be dictionaries, lists, strings, numbers, booleans, None, or custom objects. Non-serializable objects are handled by the safe_json_serialize function before JSON conversion.

Return Value

Type: str

Returns a string containing the JSON representation of the input object, formatted with 2-space indentation for readability. The output is a valid JSON string that can be parsed back into a Python object or used in JSON-compatible systems.

Dependencies

  • json

Required Imports

import json

Usage Example

# Assuming safe_json_serialize is defined
def safe_json_serialize(obj):
    if hasattr(obj, '__dict__'):
        return obj.__dict__
    return str(obj)

def to_json(obj):
    return json.dumps(safe_json_serialize(obj), indent=2)

# Example usage
data = {'name': 'John', 'age': 30, 'city': 'New York'}
json_string = to_json(data)
print(json_string)
# Output:
# {
#   "name": "John",
#   "age": 30,
#   "city": "New York"
# }

# With a list
items = [1, 2, 3, {'key': 'value'}]
json_string = to_json(items)
print(json_string)

Best Practices

  • Ensure the safe_json_serialize function is properly implemented to handle all object types you expect to serialize
  • Be aware that the indent=2 parameter creates formatted output which increases string size compared to compact JSON
  • For large objects, consider using json.dumps without indent for more compact output in production environments
  • Handle potential json.JSONDecodeError exceptions when the safe_json_serialize function doesn't properly convert objects
  • Consider adding error handling around the json.dumps call for production code
  • For API responses, you may want to use indent=None or compact separators for bandwidth efficiency

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function safe_json_serialize 75.1% similar

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

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function print_json 62.6% similar

    A utility function that prints a Python dictionary as formatted JSON with 2-space indentation to standard output.

    From: /tf/active/vicechatdev/test_acl_functions.py
  • function from_json 52.9% similar

    Parses a JSON string into a Python object, with error handling that logs parsing failures and returns None on error.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function clean_for_json_v3 50.4% 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 safe_json_dumps 50.1% 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
← Back to Browse