function to_json
Converts a Python object to a formatted JSON string with 2-space indentation, using a safe serialization helper function.
/tf/active/vicechatdev/CDocs/utils/__init__.py
200 - 210
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
-
function print_json 62.6% similar
-
function from_json 52.9% similar
-
function clean_for_json_v3 50.4% similar
-
function safe_json_dumps 50.1% similar