AQIT 0.1.0
Loading...
Searching...
No Matches
json_safe.py
Go to the documentation of this file.
1# Copyright (c) 2025-present Aquin Labs Private Limited. All Rights Reserved.
2# This file is part of the Aquin Engine. Unauthorized copying, modification,
3# distribution, or use of this file, via any medium, is strictly prohibited.
4# Proprietary and confidential. See LICENSE for terms.
5
6"""JSON helpers that never emit NaN/Inf (invalid for JS JSON.parse)."""
7from __future__ import annotations
8
9import json
10import math
11from typing import Any
12
13
14def sanitize_jsonable(obj: Any) -> Any:
15 """Recursively replace non-finite floats with None; pass through the rest."""
16 if isinstance(obj, float):
17 return None if (math.isnan(obj) or math.isinf(obj)) else obj
18 if isinstance(obj, dict):
19 return {k: sanitize_jsonable(v) for k, v in obj.items()}
20 if isinstance(obj, (list, tuple)):
21 return [sanitize_jsonable(v) for v in obj]
22 # numpy / torch scalars often duck-type to float via .item()
23 item = getattr(obj, "item", None)
24 if callable(item):
25 try:
26 return sanitize_jsonable(item())
27 except Exception:
28 return str(obj)
29 return obj
30
31
32def dumps_json_safe(obj: Any, **kwargs: Any) -> str:
33 """json.dumps with NaN/Inf stripped so receivers always get strict JSON."""
34 kwargs.setdefault("ensure_ascii", False)
35 kwargs["allow_nan"] = False
36 return json.dumps(sanitize_jsonable(obj), **kwargs)
str dumps_json_safe(Any obj, **Any kwargs)
Definition json_safe.py:36
Any sanitize_jsonable(Any obj)
Definition json_safe.py:18