strictjson.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """JSON in and out of the scripts, stricter than the json module in both directions.
  2. Input is model-written and output is read by other tools, so load() refuses
  3. what json.load admits but a conforming reader does not (NaN, Infinity, a
  4. number that overflows to infinity, nesting past the interpreter's limit), and
  5. text() keeps non-ASCII readable while escaping what UTF-8 or a JSONL line
  6. reader cannot take (an unpaired surrogate, the Unicode line separators).
  7. """
  8. from __future__ import annotations
  9. import json
  10. import math
  11. import re
  12. from collections.abc import Mapping
  13. from typing import TYPE_CHECKING, NoReturn, cast
  14. if TYPE_CHECKING:
  15. import os
  16. from typing import TypeGuard
  17. JsonMap = Mapping[str, object]
  18. # The separators a naive line reader would split a JSONL record on.
  19. _SEPARATOR_ESCAPES = {0x85: "\\u0085", 0x2028: "\\u2028", 0x2029: "\\u2029"}
  20. # The code units UTF-8 cannot encode; surrogateescape mints them from bytes.
  21. _SURROGATES = re.compile(r"[\ud800-\udfff]")
  22. def is_map(value: object) -> TypeGuard[JsonMap]:
  23. """Whether `value` is a JSON object."""
  24. return isinstance(value, dict)
  25. def is_list(value: object) -> TypeGuard[list[object]]:
  26. """Whether `value` is a JSON array."""
  27. return isinstance(value, list)
  28. def is_str(value: object) -> TypeGuard[str]:
  29. """Whether `value` is a JSON string."""
  30. return isinstance(value, str)
  31. def is_int(value: object) -> TypeGuard[int]:
  32. """Whether `value` is a JSON integer; JSON's booleans are not numbers."""
  33. return isinstance(value, int) and not isinstance(value, bool)
  34. def has_lone_surrogate(value: str) -> bool:
  35. """Whether `value` holds an unpaired surrogate, the one code unit UTF-8 cannot encode."""
  36. return _SURROGATES.search(value) is not None
  37. def _refuse(token: str) -> NoReturn:
  38. msg = f"{token} is not JSON"
  39. raise ValueError(msg)
  40. def _finite(digits: str) -> float:
  41. value = float(digits)
  42. if not math.isfinite(value):
  43. msg = f"{digits} is out of range"
  44. raise ValueError(msg)
  45. return value
  46. def load(path: str | os.PathLike[str]) -> object:
  47. """The JSON value in `path`; OSError if unreadable, ValueError if not strict JSON."""
  48. with open(path, encoding="utf-8") as handle:
  49. try:
  50. return cast("object", json.load(handle, parse_constant=_refuse, parse_float=_finite))
  51. except RecursionError as error:
  52. msg = "nested too deeply"
  53. raise ValueError(msg) from error
  54. def text(value: object, indent: int | None = None) -> str:
  55. """`value` as UTF-8-encodable JSON text: non-ASCII kept, finite only, separators escaped."""
  56. dumped = json.dumps(value, ensure_ascii=False, allow_nan=False, indent=indent)
  57. return _SURROGATES.sub(
  58. lambda match: f"\\u{ord(match.group()):04x}", dumped.translate(_SEPARATOR_ESCAPES)
  59. )