JSON encoder that handles numpy types, Decimals, and other edge cases.
| 9 | |
| 10 | class SafeJSONEncoder(json.JSONEncoder): |
| 11 | """JSON encoder that handles numpy types, Decimals, and other edge cases.""" |
| 12 | def default(self, obj): |
| 13 | if isinstance(obj, (np.integer,)): |
| 14 | return int(obj) |
| 15 | if isinstance(obj, (np.floating,)): |
| 16 | return float(obj) |
| 17 | if isinstance(obj, np.ndarray): |
| 18 | return obj.tolist() |
| 19 | if isinstance(obj, Decimal): |
| 20 | return float(obj) |
| 21 | if isinstance(obj, bytes): |
| 22 | return obj.decode('utf-8', errors='replace') |
| 23 | return super().default(obj) |
| 24 | |
| 25 | def safe_json_dumps(obj): |
| 26 | """JSON dumps with safe encoding for SSE events.""" |
| 27 | return json.dumps(obj, cls=SafeJSONEncoder, ensure_ascii=False) |
nothing calls this directly
no outgoing calls
no test coverage detected