Skip to content

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

// Pure surface of the JSONPath Tester (slug: jsonpath). A query engine for
// the core JSONPath grammar over a parsed document: $ root, .name and
// ['name'] child access, [*] and .* wildcard, ..name recursive descent,
// [n] index (negative = from end), [start:end] slice, and [a,b] union.
// Not supported (by design, documented): filter expressions [?()], script
// expressions, regex in filters. The grammar and error texts below are the
// contract a Go CLI twin must reproduce.
export interface JsonPathMatch {
  /** "$"-rooted path of the match, e.g. $.store.book[1].title. */
  path: string;
  value: unknown;
}

export type JsonPathResult =
  | { matches: JsonPathMatch[]; error: null }
  | { matches: []; error: string };

type Json = null | boolean | number | string | Json[] | { [k: string]: Json };

/** One parsed segment of the path. */
type Seg =
  | { k: 'child'; name: string }
  | { k: 'wild' }
  | { k: 'descend'; name: string }
  | { k: 'index'; n: number }
  | { k: 'slice'; start: number | null; end: number | null }
  | { k: 'union'; parts: Array<{ k: 'index'; n: number } | { k: 'child'; name: string }> };

/** Tokenize+parse a path into segments; returns null + error position on bad syntax. */
function parsePath(src: string): { segs: Seg[] } | { error: string } {
  const segs: Seg[] = [];
  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 = /^[A-Za-z_][\w-]*/.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 = /^[A-Za-z_][\w-]*/.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 (/^-?\d+$/.test(inner)) {
        segs.push({ k: 'index', n: Number(inner) });
        continue;
      }
      const quoted = /^'([^']*)'$/.test(inner) || /^"([^"]*)"$/.test(inner);
      if (quoted) {
        const m = /^['"]([^'"]*)['"]$/.exec(inner)!;
        segs.push({ k: 'child', name: m[1] });
        continue;
      }
      const slice = /^(-?\d+)?\s*:\s*(-?\d+)?$/.exec(inner);
      if (slice) {
        segs.push({
          k: 'slice',
          start: slice[1] !== undefined && slice[1] !== '' ? Number(slice[1]) : null,
          end: slice[2] !== undefined && slice[2] !== '' ? Number(slice[2]) : null,
        });
        continue;
      }
      if (inner.includes(',')) {
        const parts: Array<{ k: 'index'; n: number } | { k: 'child'; name: string }> = [];
        for (const raw of inner.split(',')) {
          const p = raw.trim();
          if (/^-?\d+$/.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 keyPath(parent: string, key: string): string {
  return `${parent}.${key}`;
}

function applySeg(nodes: JsonPathMatch[], seg: Seg, out: JsonPathMatch[]): void {
  for (const node of nodes) {
    const v = node.value as Json;
    switch (seg.k) {
      case 'child':
        if (v !== null && typeof v === 'object' && !Array.isArray(v) && seg.name in v) {
          out.push({ path: keyPath(node.path, seg.name), value: v[seg.name] });
        }
        break;
      case 'wild':
        if (Array.isArray(v)) {
          v.forEach((item, idx) => out.push({ path: `${node.path}[${idx}]`, value: item }));
        } else if (v !== null && typeof v === 'object') {
          for (const key of Object.keys(v)) out.push({ path: keyPath(node.path, key), value: v[key] });
        }
        break;
      case 'descend': {
        const visit = (val: Json, path: string): void => {
          if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
            for (const key of Object.keys(val)) {
              const child = val[key];
              if (key === seg.name) out.push({ path: keyPath(path, key), value: child });
              visit(child, keyPath(path, key));
            }
          } else if (Array.isArray(val)) {
            val.forEach((item, idx) => visit(item, `${path}[${idx}]`));
          }
        };
        visit(v, node.path);
        break;
      }
      case '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: `${node.path}[${idx}]`, value: v[idx] });
        }
        break;
      }
      case '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: `${node.path}[${idx}]`, value: v[idx] });
        }
        break;
      }
    }
  }
}

/** Evaluate a JSONPath expression against a JSON document. */
export function queryJsonPath(docRaw: string, path: string): JsonPathResult {
  if (!docRaw.trim() || !path.trim()) {
    return { matches: [], error: 'Both a document and a path are required' };
  }
  let doc: Json;
  try {
    doc = JSON.parse(docRaw) as Json;
  } catch (e) {
    return { matches: [], error: e instanceof Error ? e.message : 'Invalid JSON' };
  }
  const parsed = parsePath(path.trim());
  if ('error' in parsed) return { matches: [], error: parsed.error };
  let current: JsonPathMatch[] = [{ path: '$', value: doc }];
  for (const seg of parsed.segs) {
    // Unions collect their members per node; the placeholder index branch
    // above never runs because we special-case unions here.
    if (seg.k === 'union') {
      const next: JsonPathMatch[] = [];
      for (const node of current) {
        for (const part of seg.parts) applySeg([node], part, next);
      }
      current = next;
      continue;
    }
    const next: JsonPathMatch[] = [];
    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 →