|
| 1 | +"""Adapt the standalone JSON parser to runtime values and serialization rules.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json as _json |
| 6 | +import math |
| 7 | +from collections.abc import Mapping |
| 8 | + |
| 9 | +import JSON as _standalone |
| 10 | + |
| 11 | +from ._array import Array |
| 12 | +from ._object import Object, own_entries |
| 13 | +from ._string import String |
| 14 | +from ._values import is_number, number_string, to_number, to_string, undefined |
| 15 | + |
| 16 | + |
| 17 | +def _runtime(value): |
| 18 | + if isinstance(value, dict): |
| 19 | + return Object({key: _runtime(child) for key, child in dict.items(value)}) |
| 20 | + if isinstance(value, list): |
| 21 | + return Array.of(*(_runtime(child) for child in value)) |
| 22 | + if isinstance(value, str): |
| 23 | + return String(value) |
| 24 | + return to_number(value) if is_number(value) else value |
| 25 | + |
| 26 | + |
| 27 | +def _quote(value): |
| 28 | + # Delegate escaping to the companion, preserving normal Unicode while |
| 29 | + # escaping lone surrogates as required by well-formed JSON.stringify. |
| 30 | + value = value.encode("utf-16-le", "surrogatepass").decode("utf-16-le", "surrogatepass") |
| 31 | + quoted = _standalone.stringify(value, ensure_ascii=False) |
| 32 | + return "".join(f"\\u{ord(char):04x}" if 0xD800 <= ord(char) <= 0xDFFF else char for char in quoted) |
| 33 | + |
| 34 | + |
| 35 | +class _JSON: |
| 36 | + JSONDecodeError = _standalone.JSONDecodeError |
| 37 | + |
| 38 | + @staticmethod |
| 39 | + def parse(text): |
| 40 | + """Parse JSON after JavaScript string conversion; no reviver overload.""" |
| 41 | + if isinstance(text, (bytes, bytearray)): |
| 42 | + raise TypeError("JavaScript.JSON.parse expects text, not bytes") |
| 43 | + def reject_constant(value): |
| 44 | + raise ValueError(f"{value} is not a valid JSON numeric constant") |
| 45 | + |
| 46 | + # The standalone parser preserves Python integers. Select binary64 |
| 47 | + # decoder hooks here so nested -0 and large integers retain JS semantics. |
| 48 | + value = _json.loads( |
| 49 | + to_string(text), parse_int=float, parse_float=float, |
| 50 | + parse_constant=reject_constant, |
| 51 | + ) |
| 52 | + return _runtime(value) |
| 53 | + |
| 54 | + @staticmethod |
| 55 | + def stringify(value=undefined, replacer=undefined, space=undefined): |
| 56 | + """Serialize supported values; replacers and toJSON hooks are not supported.""" |
| 57 | + if replacer is not undefined and replacer is not None: |
| 58 | + raise NotImplementedError("JSON replacers are not supported") |
| 59 | + if is_number(space): |
| 60 | + number = to_number(space) |
| 61 | + gap = " " * (0 if math.isnan(number) else int(max(0, min(number, 10)))) |
| 62 | + elif isinstance(space, str): |
| 63 | + gap = String(space).slice(0, 10).valueOf() |
| 64 | + else: |
| 65 | + gap = "" |
| 66 | + active = set() |
| 67 | + |
| 68 | + def encode(child, depth=0): |
| 69 | + if child is undefined or callable(child): |
| 70 | + return undefined |
| 71 | + if child is None: |
| 72 | + return "null" |
| 73 | + if isinstance(child, bool): |
| 74 | + return "true" if child else "false" |
| 75 | + if isinstance(child, str): |
| 76 | + return _quote(child) |
| 77 | + if is_number(child): |
| 78 | + return number_string(child) if math.isfinite(to_number(child)) else "null" |
| 79 | + if not isinstance(child, (Object, Array, Mapping, list, tuple)): |
| 80 | + raise TypeError(f"Unsupported JSON value: {type(child).__name__}") |
| 81 | + if isinstance(child, (Object, Mapping)): |
| 82 | + if any(key == "toJSON" and callable(item) for key, item in own_entries(child)): |
| 83 | + raise NotImplementedError("JSON toJSON hooks are not supported") |
| 84 | + identity = id(child) |
| 85 | + if identity in active: |
| 86 | + raise TypeError("Converting circular structure to JSON") |
| 87 | + active.add(identity) |
| 88 | + try: |
| 89 | + array = isinstance(child, (Array, list, tuple)) |
| 90 | + parts = [] |
| 91 | + if array: |
| 92 | + for item in child: |
| 93 | + text = encode(item, depth + 1) |
| 94 | + parts.append("null" if text is undefined else text) |
| 95 | + else: |
| 96 | + for key, item in own_entries(child): |
| 97 | + text = encode(item, depth + 1) |
| 98 | + if text is not undefined: |
| 99 | + parts.append(_quote(key) + (": " if gap else ":") + text) |
| 100 | + left, right = ("[", "]") if array else ("{", "}") |
| 101 | + if not parts: |
| 102 | + return left + right |
| 103 | + if not gap: |
| 104 | + return left + ",".join(parts) + right |
| 105 | + prefix = gap * (depth + 1) |
| 106 | + return left + "\n" + prefix + (",\n" + prefix).join(parts) + "\n" + gap * depth + right |
| 107 | + finally: |
| 108 | + active.remove(identity) |
| 109 | + |
| 110 | + result = encode(value) |
| 111 | + return result if result is undefined else String(result) |
| 112 | + |
| 113 | + |
| 114 | +JSON = _JSON() |
0 commit comments