Skip to content

JSON Tree Explorer — TypeScript source

Paste JSON and explore it as a navigable tree: every node with its path, type, and value preview. Filter by key, path, or value — ancestors of matches stay visible — with live type counts for the whole document.

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

// Pure surface of the json-tree tool (slug: json-tree). The island renders
// these rows; the Go twin reproduces flatten/filter/counts deterministically:
// preorder walk in JS insertion order, paths as $.a[0].b, primitives carry a
// preview string, and filter matching is a case-insensitive substring test on
// key, path, and stringified value — never on type names alone.
export type JsonPrimitiveType = 'string' | 'number' | 'boolean' | 'null';
export type JsonNodeType = 'object' | 'array' | JsonPrimitiveType;

export interface TreeRow {
  /** Stable row id: the path itself. */
  id: string;
  /** JSONPath-style path: $.a, $.a[0], $.a[0].b */
  path: string;
  /** Last path segment; '' for the root row. */
  key: string;
  depth: number;
  type: JsonNodeType;
  /** For primitives: the source-ish preview (strings unquoted truncated at 80). */
  preview: string | null;
  /** For object/array rows: number of direct children. */
  childCount: number | null;
}

function typeOf(v: unknown): JsonNodeType {
  if (v === null) return 'null';
  if (Array.isArray(v)) return 'array';
  if (typeof v === 'object') return 'object';
  return typeof v as JsonPrimitiveType;
}

function previewOf(v: unknown): string {
  if (v === null) return 'null';
  if (typeof v === 'string') return v.length > 80 ? v.slice(0, 79) + '…' : v;
  return String(v); // number | boolean — callers only pass primitives
}

/** Flatten parsed JSON into preorder rows. Root row comes first with path '$'. */
export function flattenJson(value: unknown): TreeRow[] {
  const rows: TreeRow[] = [];

  const walk = (v: unknown, path: string, key: string, depth: number): void => {
    const type = typeOf(v);
    const isBranch = type === 'object' || type === 'array';
    rows.push({
      id: path,
      path,
      key,
      depth,
      type,
      preview: isBranch ? null : previewOf(v),
      childCount: isBranch
        ? type === 'array'
          ? (v as unknown[]).length
          : Object.keys(v as object).length
        : null,
    });
    if (type === 'array') {
      (v as unknown[]).forEach((item, i) => walk(item, `${path}[${i}]`, String(i), depth + 1));
    } else if (type === 'object') {
      for (const [k, item] of Object.entries(v as object)) walk(item, `${path}.${k}`, k, depth + 1);
    }
  };

  walk(value, '$', '', 0);
  return rows;
}

export interface FilterResult {
  rows: TreeRow[];
  /** Paths of rows whose OWN text matched (for highlight in the island). */
  matches: Set<string>;
  /** Match count = rows kept, not text hits. */
  matchCount: number;
}

/** Keep rows whose key, path, or preview matches the query (case-insensitive
 *  substring). Empty query returns all rows with an empty match set. Branch
 *  rows match when a descendant match keeps them alive (kept for structure). */
export function filterRows(rows: TreeRow[], query: string): FilterResult {
  const q = query.trim().toLowerCase();
  if (!q) return { rows, matches: new Set(), matchCount: rows.length };

  const ownMatch = rows.filter((r) => {
    const key = r.key.toLowerCase();
    const path = r.path.toLowerCase();
    const prev = (r.preview ?? '').toLowerCase();
    return key.includes(q) || path.includes(q) || prev.includes(q);
  });
  const matches = new Set(ownMatch.map((r) => r.id));
  // Keep ancestors of matches so the tree stays navigable.
  const keep = new Set<string>();
  for (const r of ownMatch) {
    let path = r.id;
    keep.add(path);
    while (path !== '$') {
      // Parent = strip the last .key or [i] segment, whichever ends later.
      path = path.slice(0, Math.max(path.lastIndexOf('.'), path.lastIndexOf('[')));
      keep.add(path);
    }
  }
  const kept = rows.filter((r) => keep.has(r.id));
  return { rows: kept, matches, matchCount: kept.length };
}

/** Count rows per type, for the island's summary chips. */
export function typeCounts(rows: TreeRow[]): Record<JsonNodeType, number> {
  const counts: Record<JsonNodeType, number> = {
    object: 0,
    array: 0,
    string: 0,
    number: 0,
    boolean: 0,
    null: 0,
  };
  for (const r of rows) counts[r.type] += 1;
  return counts;
}

/** Parse + flatten + count in one step for the island entry point. */
export type ParseToTreeResult =
  | { rows: TreeRow[]; counts: Record<JsonNodeType, number>; error: null }
  /** Empty input: no rows, no error — the island shows nothing. */
  | { rows: []; counts: null; error: null }
  | { rows: []; counts: null; error: string };

export function parseToTree(raw: string): ParseToTreeResult {
  const text = raw.trim();
  if (!text) return { rows: [], counts: null, error: null };
  try {
    const rows = flattenJson(JSON.parse(text));
    return { rows, counts: typeCounts(rows), error: null };
  } catch (e) {
    return { rows: [], counts: null, error: e instanceof Error ? e.message : 'Invalid JSON' };
  }
}

Also available in 1 other language

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