Skip to content

JSONPath Tester — PHP 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 PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
// jsonpath — JSONPath query engine. PHP 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. json_decode keeps objects as stdClass (properties in document
// order), so wildcard/descent match order matches the TS contract; path
// errors are byte-for-byte the TS texts; parse failures surface
// json_last_error_msg(). Filter [?()] and script expressions are
// unsupported by design. Stdlib only (ext-json + ext-pcre).

/** One parsed segment of the path (kinds: child, wild, descend, index, slice, union). */

/** Name scan: [A-Za-z_][A-Za-z0-9_-]* at $off, or null. */
function jsonpath_name_at(string $s, int $off): ?string {
    if ($off >= strlen($s) || preg_match('/[A-Za-z_][A-Za-z0-9_-]*/', $s, $m, 0, $off) !== 1) return null;
    return $m[0];
}

/** Strict JSON int literal ("-?\d+"). */
function jsonpath_is_int(string $t): bool { return preg_match('/^-?[0-9]+$/', $t) === 1; }

/** '...' or "..." with the SAME quotes and none inside (bracket child form). */
function jsonpath_same_quote(string $t): ?string {
    if (strlen($t) < 2) return null;
    $q = $t[0];
    if (($q !== "'" && $q !== '"') || $t[strlen($t) - 1] !== $q) return null;
    if (strpos($t, $q, 1) !== strlen($t) - 1) return null;
    return substr($t, 1, -1);
}

/** Any quote ... any quote with no quotes inside (union member form). */
function jsonpath_union_quote(string $t): ?string {
    if (strlen($t) < 2 || ($t[0] !== "'" && $t[0] !== '"')) return null;
    if ($t[strlen($t) - 1] !== "'" && $t[strlen($t) - 1] !== '"') return null;
    $mid = substr($t, 1, -1);
    if (strpbrk($mid, "'\"") !== false) return null;
    return $mid;
}

/** Tokenize+parse a path into segments; returns [segments, null] or [null, error]. */
function jsonpath_parse_path(string $src): array {
    $segs = [];
    if ($src === '' || $src[0] !== '$') return [null, 'path must start with $'];
    $i = 1;
    $n = strlen($src);
    while ($i < $n) {
        $ch = $src[$i];
        if ($ch === '.') {
            if (($src[$i + 1] ?? '') === '.') {
                $i += 2;
                $m = jsonpath_name_at($src, $i);
                if ($m === null) return [null, "expected a name after \"..\" at position {$i}"];
                $segs[] = ['k' => 'descend', 'name' => $m];
                $i += strlen($m);
            } else {
                $i += 1;
                if (($src[$i] ?? '') === '*') { $segs[] = ['k' => 'wild']; $i += 1; continue; }
                $m = jsonpath_name_at($src, $i);
                if ($m === null) return [null, "expected a name or * after \".\" at position {$i}"];
                $segs[] = ['k' => 'child', 'name' => $m];
                $i += strlen($m);
            }
        } elseif ($ch === '[') {
            $close = strpos($src, ']', $i);
            if ($close === false) return [null, "unclosed [ at position {$i}"];
            $inner = trim(substr($src, $i + 1, $close - $i - 1));
            $i = $close + 1;
            if ($inner === '*') { $segs[] = ['k' => 'wild']; continue; }
            if (jsonpath_is_int($inner)) { $segs[] = ['k' => 'index', 'n' => (int)$inner]; continue; }
            if (($nm = jsonpath_same_quote($inner)) !== null) { $segs[] = ['k' => 'child', 'name' => $nm]; continue; }
            if (preg_match('/^(-?[0-9]+)?\s*:\s*(-?[0-9]+)?$/', $inner) === 1) {
                [$a, $b] = explode(':', $inner);
                $a = trim($a); $b = trim($b);
                $segs[] = ['k' => 'slice', 'start' => $a === '' ? null : (int)$a, 'end' => $b === '' ? null : (int)$b];
                continue;
            }
            if (strpos($inner, ',') !== false) {
                $parts = [];
                foreach (explode(',', $inner) as $raw) {
                    $p = trim($raw);
                    if (jsonpath_is_int($p)) { $parts[] = ['k' => 'index', 'n' => (int)$p]; }
                    elseif (($nm = jsonpath_union_quote($p)) !== null) { $parts[] = ['k' => 'child', 'name' => $nm]; }
                    else return [null, "bad union member \"{$p}\" in [{$inner}]"];
                }
                $segs[] = ['k' => 'union', 'parts' => $parts];
                continue;
            }
            return [null, "unsupported selector [{$inner}]"];
        } else {
            return [null, "unexpected character \"{$ch}\" at position {$i}"];
        }
    }
    return [$segs, null];
}

/** Recursive descent: object keys are checked then recursed (TS order). */
function jsonpath_descend($val, string $p, string $name, array &$out): void {
    if (is_object($val)) {
        foreach (get_object_vars($val) as $key => $child) {
            $cp = "{$p}.{$key}";
            if ($key === $name) $out[] = ['path' => $cp, 'value' => $child];
            jsonpath_descend($child, $cp, $name, $out);
        }
    } elseif (is_array($val)) {
        foreach ($val as $idx => $item) jsonpath_descend($item, "{$p}[{$idx}]", $name, $out);
    }
}

/** Apply one segment to every pending node, appending matches to $out. */
function jsonpath_apply(array $nodes, array $seg, array &$out): void {
    foreach ($nodes as $node) {
        $p = $node['path'];
        $v = $node['value'];
        switch ($seg['k']) {
            case 'child':
                if (is_object($v) && property_exists($v, $seg['name'])) {
                    $out[] = ['path' => "{$p}.{$seg['name']}", 'value' => $v->{$seg['name']}];
                }
                break;
            case 'wild':
                if (is_array($v)) {
                    foreach ($v as $idx => $item) $out[] = ['path' => "{$p}[{$idx}]", 'value' => $item];
                } elseif (is_object($v)) {
                    foreach (get_object_vars($v) as $key => $val) $out[] = ['path' => "{$p}.{$key}", 'value' => $val];
                }
                break;
            case 'descend':
                jsonpath_descend($v, $p, $seg['name'], $out);
                break;
            case 'index':
                if (is_array($v)) {
                    $idx = $seg['n'] < 0 ? count($v) + $seg['n'] : $seg['n'];
                    if ($idx >= 0 && $idx < count($v)) $out[] = ['path' => "{$p}[{$idx}]", 'value' => $v[$idx]];
                }
                break;
            case 'slice':
                if (is_array($v)) {
                    $len = count($v);
                    $start = $seg['start'] === null ? 0 : ($seg['start'] < 0 ? max($len + $seg['start'], 0) : min($seg['start'], $len));
                    $end = $seg['end'] === null ? $len : ($seg['end'] < 0 ? max($len + $seg['end'], 0) : min($seg['end'], $len));
                    for ($idx = $start; $idx < $end; $idx++) $out[] = ['path' => "{$p}[{$idx}]", 'value' => $v[$idx]];
                }
                break;
        }
    }
}

/** Evaluate a JSONPath expression against a JSON document. */
function query_json_path(string $doc_raw, string $path): array {
    if (trim($doc_raw) === '' || trim($path) === '') {
        return ['matches' => [], 'error' => 'Both a document and a path are required'];
    }
    $doc = json_decode($doc_raw, false, 512);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return ['matches' => [], 'error' => json_last_error_msg()];
    }
    [$segs, $err] = jsonpath_parse_path(trim($path));
    if ($err !== null) return ['matches' => [], 'error' => $err];
    $current = [['path' => '$', 'value' => $doc]];
    foreach ($segs as $seg) {
        $next = [];
        if ($seg['k'] === 'union') {
            foreach ($current as $node) {
                foreach ($seg['parts'] as $part) jsonpath_apply([$node], $part, $next);
            }
        } else {
            jsonpath_apply($current, $seg, $next);
        }
        $current = $next;
    }
    return ['matches' => $current, 'error' => null];
}

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 →