vibe.serialization¶
Safe JSON serialization utilities.
This module provides utilities for safely converting Python objects to JSON-serializable form, handling edge cases like: - Dataclasses and Pydantic models - Circular references (via max_depth) - Non-serializable objects (fallback to repr) - Message objects (via message_to_dict)
Usage
from vibe.serialization import safe_json_serialize
Convert any object to JSON-serializable form¶
data = safe_json_serialize(complex_object)
Then use json.dumps safely¶
json_str = json.dumps(data)
safe_json_serialize ¶
safe_json_serialize(obj: object, max_depth: int = DEFAULT_SERIALIZATION_DEPTH) -> object
Convert any object to a JSON-serializable form.
Handles common Python types, dataclasses, Pydantic models, and Message objects. Falls back to repr() for truly non-serializable objects.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Examples:
>>> safe_json_serialize({"a": 1, "b": [2, 3]})
{'a': 1, 'b': [2, 3]}
>>> safe_json_serialize(UserMessage(content="hello"))
{'type': 'user', 'content': 'hello', 'is_auto_reply': False}
>>> safe_json_serialize(object()) # Falls back to repr
'<object object at 0x...>'
json_serialize_or_repr ¶
json_serialize_or_repr(obj: object) -> str
Serialize object to JSON string, falling back to repr on failure.
This is a convenience function for cases where you need a string representation.
| Parameters: |
|
|---|
| Returns: |
|
|---|