"""Compact JSON discovery and explicit, lossless field selection.""" import json import re _TOKEN = re.compile(r"\.([A-Za-z_][A-Za-z0-9_-]*)|\[(\*|0|[1-9][0-9]{0,8})\]|\[(\"(?:[^\"\\]|\\.)*\")\]") def select(data: object, path: str) -> object: if not path.startswith("$"): raise ValueError('Use a path starting with $, e.g. $.info.name or $[*]["foo.bar"]') nodes = [data] many = False pos = 1 while pos < len(path): match = _TOKEN.match(path, pos) if match is None: raise ValueError(f"Unsupported JSON path at character {pos}") field, index, quoted = match.groups() pos = match.end() if field is not None or quoted is not None: key = field if field is not None else json.loads(quoted) nodes = [n[key] for n in nodes if isinstance(n, dict) and key in n] elif index == "*": many = True nodes = [v for n in nodes if isinstance(n, list) for v in n] else: i = int(index) nodes = [n[i] for n in nodes if isinstance(n, list) and i < len(n)] if many: return nodes if not nodes: raise ValueError("No such JSON field or index") return nodes[0] def shape(value: object, depth: int = 0) -> object: if isinstance(value, dict): info = {"type": "object", "count": len(value)} if depth < 2: from itertools import islice info["fields"] = {k: shape(v, depth + 1) for k, v in islice(value.items(), 16)} return info if isinstance(value, list): info = {"type": "array", "count": len(value)} if value and depth < 2: info["first_item_shape"] = shape(value[0], depth + 1) return info return {str: "string", int: "integer", float: "number", bool: "boolean", type(None): "null"}[type(value)] def render_json(body: bytes, mode: str, value: str | None) -> str: data = json.loads(body) if mode == "outline": data = shape(data) elif mode == "jsonpath" and value is not None: data = select(data, value) elif mode != "text": raise ValueError("JSON supports outline, jsonpath or text") return json.dumps(data, ensure_ascii=False, separators=(",", ":"))