Skip to content

JSONPath Tester — Python source

Run JSONPath queries against any document: child access, wildcards, recursive descent, indexes, slices and unions, with every match shown at its full path. Runs locally in your browser with a shareable link.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""jsonpath — JSONPath query engine. Python port (canonical TS:
src/lib/jsonpath.ts; Go twin: cli/jsonpath). Tokenizes a core-grammar path
— "$" root, ".name" / "['name']" child, ".*" / "[*]" wildcard, "..name"
recursive descent, "[n]" index (negative = from end), "[start:end]" slice,
"[a,b]" union of indexes and quoted names — and matches it over a parsed
document. Dicts keep JSON key insertion order, so wildcard/descent match
order matches the TS contract; path errors are byte-for-byte the TS texts;
parse failures surface the parser's message. Filter [?()] and script
expressions are unsupported by design. Stdlib only (json + re). Segments
are tagged tuples: ('child', name), ('wild',), ('descend', name),
('index', n), ('slice', start, end), ('union', parts) — each part a
('index', n) or ('child', name) tuple. Never raises.
"""
import json
import re

NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*")
INT = re.compile(r"-?[0-9]+\Z")
SLICE = re.compile(r"(-?[0-9]+)?\s*:\s*(-?[0-9]+)?\Z")
SAME_QUOTE = (re.compile(r"'[^']*'\Z"), re.compile(r'"[^"]*"\Z'))
UNION_QUOTE = re.compile(r"['\"][^'\"]*['\"]\Z")


def _int_or_none(g):
    """Slice side: absent/empty group is None (open end), else the int."""
    return int(g) if g else None


def parse_path(src):
    """Returns (segments, None) or (None, error) on bad syntax."""
    segs = []
    if not src.startswith("$"):
        return None, "path must start with $"
    i = 1
    n = len(src)
    while i < n:
        ch = src[i]
        if ch == ".":
            if src[i + 1 : i + 2] == ".":
                i += 2
                m = NAME.match(src, i)
                if not m:
                    return None, f'expected a name after ".." at position {i}'
                segs.append(("descend", m.group()))
                i = m.end()
            else:
                i += 1
                if src[i : i + 1] == "*":
                    segs.append(("wild",))
                    i += 1
                    continue
                m = NAME.match(src, i)
                if not m:
                    return None, f'expected a name or * after "." at position {i}'
                segs.append(("child", m.group()))
                i = m.end()
        elif ch == "[":
            close = src.find("]", i)
            if close == -1:
                return None, f"unclosed [ at position {i}"
            inner = src[i + 1 : close].strip()
            i = close + 1
            if inner == "*":
                segs.append(("wild",))
                continue
            if INT.match(inner):
                segs.append(("index", int(inner)))
                continue
            if any(q.match(inner) for q in SAME_QUOTE):
                segs.append(("child", inner[1:-1]))
                continue
            sl = SLICE.match(inner)
            if sl:
                segs.append(("slice", _int_or_none(sl.group(1)), _int_or_none(sl.group(2))))
                continue
            if "," in inner:
                parts = []
                for raw in inner.split(","):
                    p = raw.strip()
                    if INT.match(p):
                        parts.append(("index", int(p)))
                    elif UNION_QUOTE.match(p):
                        parts.append(("child", p[1:-1]))
                    else:
                        return None, f'bad union member "{p}" in [{inner}]'
                segs.append(("union", parts))
                continue
            return None, f"unsupported selector [{inner}]"
        else:
            return None, f'unexpected character "{ch}" at position {i}'
    return segs, None


def _descend(val, path, name, out):
    """Recursive descent: object keys are checked then recursed (TS order)."""
    if isinstance(val, dict):
        for key, child in val.items():
            cp = f"{path}.{key}"
            if key == name:
                out.append((cp, child))
            _descend(child, cp, name, out)
    elif isinstance(val, list):
        for idx, item in enumerate(val):
            _descend(item, f"{path}[{idx}]", name, out)


def _apply(nodes, seg, out):
    kind = seg[0]
    for path, v in nodes:
        if kind == "child":
            if isinstance(v, dict) and seg[1] in v:
                out.append((f"{path}.{seg[1]}", v[seg[1]]))
        elif kind == "wild":
            if isinstance(v, list):
                for idx, item in enumerate(v):
                    out.append((f"{path}[{idx}]", item))
            elif isinstance(v, dict):
                for key, val in v.items():
                    out.append((f"{path}.{key}", val))
        elif kind == "descend":
            _descend(v, path, seg[1], out)
        elif kind == "index":
            if isinstance(v, list):
                idx = len(v) + seg[1] if seg[1] < 0 else seg[1]
                if 0 <= idx < len(v):
                    out.append((f"{path}[{idx}]", v[idx]))
        elif kind == "slice":
            if isinstance(v, list):
                ln = len(v)
                start = 0 if seg[1] is None else (max(ln + seg[1], 0) if seg[1] < 0 else min(seg[1], ln))
                end = ln if seg[2] is None else (max(ln + seg[2], 0) if seg[2] < 0 else min(seg[2], ln))
                for idx in range(start, end):
                    out.append((f"{path}[{idx}]", v[idx]))


def query_json_path(doc_raw, path):
    """Evaluate a JSONPath expression against a JSON document."""
    if not doc_raw.strip() or not path.strip():
        return {"matches": [], "error": "Both a document and a path are required"}
    try:
        doc = json.loads(doc_raw)
    except ValueError as e:
        return {"matches": [], "error": str(e) or "Invalid JSON"}
    segs, err = parse_path(path.strip())
    if err:
        return {"matches": [], "error": err}
    current = [("$", doc)]
    for seg in segs:
        nxt = []
        if seg[0] == "union":
            for node in current:
                for part in seg[1]:
                    _apply([node], part, nxt)
        else:
            _apply(current, seg, nxt)
        current = nxt
    return {"matches": [{"path": p, "value": v} for p, v in current], "error": None}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →