Recursively convert objects into JSON-encodable primitives.
(value: Any)
| 16 | |
| 17 | |
| 18 | def _json_safe(value: Any) -> Any: |
| 19 | """Recursively convert objects into JSON-encodable primitives.""" |
| 20 | if value is None or isinstance(value, (str, int, float, bool)): |
| 21 | return value |
| 22 | if isinstance(value, dict): |
| 23 | return {str(key): _json_safe(val) for key, val in value.items()} |
| 24 | if isinstance(value, (list, tuple, set)): |
| 25 | return [_json_safe(item) for item in value] |
| 26 | to_dict = getattr(value, "to_dict", None) |
| 27 | if callable(to_dict): |
| 28 | try: |
| 29 | return _json_safe(to_dict()) |
| 30 | except Exception: |
| 31 | pass |
| 32 | if hasattr(value, "__dict__"): |
| 33 | try: |
| 34 | return _json_safe(vars(value)) |
| 35 | except Exception: |
| 36 | pass |
| 37 | return str(value) |
| 38 | |
| 39 | |
| 40 | @dataclass |