Skip to content

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

// jsonpath — JSONPath query engine. JavaScript 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. Object key insertion order drives wildcard/descent match order;
// path-error texts are byte-for-byte the TS contract. Filter [?()] and
// script expressions are unsupported by design. Stdlib only: JSON.parse.

/**
 * One match: the "$"-rooted path, e.g. `$.store.book[1].title`, plus value.
 * @typedef {{path: string, value: unknown}} JsonPathMatch
 * @typedef {{matches: JsonPathMatch[], error: null} | {matches: [], error: string}} JsonPathResult
 */

const NAME = /^[A-Za-z_][\w-]*/;
const INT = /^-?\d+$/;
const SLICE = /^(-?\d+)?\s*:\s*(-?\d+)?$/;

/** Tokenize+parse a path into segments; returns {segs} or {error} on bad syntax. */
function parsePath(src) {
  const segs = [];
  let i = 0;
  if (src[0] !== '$') return { error: 'path must start with $' };
  i = 1;
  while (i < src.length) {
    const ch = src[i];
    if (ch === '.') {
      if (src[i + 1] === '.') {
        i += 2;
        const m = NAME.exec(src.slice(i));
        if (!m) return { error: `expected a name after ".." at position ${i}` };
        segs.push({ k: 'descend', name: m[0] });
        i += m[0].length;
      } else {
        i += 1;
        if (src[i] === '*') {
          segs.push({ k: 'wild' });
          i += 1;
          continue;
        }
        const m = NAME.exec(src.slice(i));
        if (!m) return { error: `expected a name or * after "." at position ${i}` };
        segs.push({ k: 'child', name: m[0] });
        i += m[0].length;
      }
    } else if (ch === '[') {
      const close = src.indexOf(']', i);
      if (close === -1) return { error: `unclosed [ at position ${i}` };
      const inner = src.slice(i + 1, close).trim();
      i = close + 1;
      if (inner === '*') {
        segs.push({ k: 'wild' });
        continue;
      }
      if (INT.test(inner)) {
        segs.push({ k: 'index', n: Number(inner) });
        continue;
      }
      if (/^'([^']*)'$/.test(inner) || /^"([^"]*)"$/.test(inner)) {
        segs.push({ k: 'child', name: inner.slice(1, -1) });
        continue;
      }
      const sl = SLICE.exec(inner);
      if (sl) {
        segs.push({
          k: 'slice',
          start: sl[1] !== undefined && sl[1] !== '' ? Number(sl[1]) : null,
          end: sl[2] !== undefined && sl[2] !== '' ? Number(sl[2]) : null,
        });
        continue;
      }
      if (inner.includes(',')) {
        const parts = [];
        for (const raw of inner.split(',')) {
          const p = raw.trim();
          if (INT.test(p)) parts.push({ k: 'index', n: Number(p) });
          else if (/^['"][^'"]*['"]$/.test(p)) parts.push({ k: 'child', name: p.slice(1, -1) });
          else return { error: `bad union member "${p}" in [${inner}]` };
        }
        segs.push({ k: 'union', parts });
        continue;
      }
      return { error: `unsupported selector [${inner}]` };
    } else {
      return { error: `unexpected character "${ch}" at position ${i}` };
    }
  }
  return { segs };
}

function applySeg(nodes, seg, out) {
  for (const { path, value: v } of nodes) {
    if (seg.k === 'child') {
      if (v !== null && typeof v === 'object' && !Array.isArray(v) && seg.name in v) {
        out.push({ path: `${path}.${seg.name}`, value: v[seg.name] });
      }
    } else if (seg.k === 'wild') {
      if (Array.isArray(v)) {
        v.forEach((item, idx) => out.push({ path: `${path}[${idx}]`, value: item }));
      } else if (v !== null && typeof v === 'object') {
        for (const key of Object.keys(v)) out.push({ path: `${path}.${key}`, value: v[key] });
      }
    } else if (seg.k === 'descend') {
      const visit = (val, p) => {
        if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
          for (const key of Object.keys(val)) {
            const child = val[key];
            const cp = `${p}.${key}`;
            if (key === seg.name) out.push({ path: cp, value: child });
            visit(child, cp);
          }
        } else if (Array.isArray(val)) {
          val.forEach((item, idx) => visit(item, `${p}[${idx}]`));
        }
      };
      visit(v, path);
    } else if (seg.k === 'index') {
      if (Array.isArray(v)) {
        const idx = seg.n < 0 ? v.length + seg.n : seg.n;
        if (idx >= 0 && idx < v.length) out.push({ path: `${path}[${idx}]`, value: v[idx] });
      }
    } else if (seg.k === 'slice') {
      if (Array.isArray(v)) {
        const len = v.length;
        const start = seg.start === null ? 0 : seg.start < 0 ? Math.max(len + seg.start, 0) : Math.min(seg.start, len);
        const end = seg.end === null ? len : seg.end < 0 ? Math.max(len + seg.end, 0) : Math.min(seg.end, len);
        for (let idx = start; idx < end; idx++) out.push({ path: `${path}[${idx}]`, value: v[idx] });
      }
    }
  }
}

/** Evaluate a JSONPath expression against a JSON document. */
export function queryJsonPath(docRaw, path) {
  if (!docRaw.trim() || !path.trim()) {
    return { matches: [], error: 'Both a document and a path are required' };
  }
  let doc;
  try {
    doc = JSON.parse(docRaw);
  } catch (e) {
    return { matches: [], error: e instanceof Error ? e.message : 'Invalid JSON' };
  }
  const parsed = parsePath(path.trim());
  if (parsed.error) return { matches: [], error: parsed.error };
  let current = [{ path: '$', value: doc }];
  for (const seg of parsed.segs) {
    const next = [];
    if (seg.k === 'union') {
      for (const node of current) {
        for (const part of seg.parts) applySeg([node], part, next);
      }
    } else {
      applySeg(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 →