Skip to content

JSON Diff — TypeScript source

Compare two JSON documents structurally: added, removed and changed values reported at exact paths instead of raw text lines. 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 JSON Diff tool (slug: json-diff). Structural, not
// textual: walks both parsed documents and reports added/removed/changed
// values at "$"-rooted paths (objects by key union, arrays by index — no LCS
// alignment; a shifted array reports every moved index, by design). These
// rules are the contract a Go CLI twin must reproduce.
export interface JsonDiffChange {
  /** "$"-rooted path: `$.name`, `$.users[0]`, `$[2]`. Root itself is `$`. */
  path: string;
  type: 'added' | 'removed' | 'changed';
  /** Value on the left document. Absent when type is 'added'. */
  before?: unknown;
  /** Value on the right document. Absent when type is 'removed'. */
  after?: unknown;
}

export type JsonDiffResult =
  | { changes: JsonDiffChange[]; same: boolean; error: null }
  | { changes: []; same: false; error: string };

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

function isObject(v: Json): v is { [k: string]: Json } {
  return v !== null && typeof v === 'object' && !Array.isArray(v);
}

function deepEqual(a: Json, b: Json): boolean {
  if (a === b) return true;
  if (Array.isArray(a) && Array.isArray(b)) {
    return a.length === b.length && a.every((el, i) => deepEqual(el, b[i]));
  }
  if (isObject(a) && isObject(b)) {
    const ka = Object.keys(a);
    const kb = Object.keys(b);
    return ka.length === kb.length && ka.every((k) => k in b && deepEqual(a[k], b[k]));
  }
  return false;
}

function walk(left: Json, right: Json, path: string, out: JsonDiffChange[]): void {
  if (deepEqual(left, right)) return;

  if (isObject(left) && isObject(right)) {
    for (const key of [...new Set([...Object.keys(left), ...Object.keys(right)])].sort()) {
      const child = `${path}.${key}`;
      if (!(key in left)) out.push({ path: child, type: 'added', after: right[key] });
      else if (!(key in right)) out.push({ path: child, type: 'removed', before: left[key] });
      else walk(left[key], right[key], child, out);
    }
    return;
  }

  if (Array.isArray(left) && Array.isArray(right)) {
    const shared = Math.min(left.length, right.length);
    for (let i = 0; i < shared; i++) walk(left[i], right[i], `${path}[${i}]`, out);
    for (let i = shared; i < right.length; i++) out.push({ path: `${path}[${i}]`, type: 'added', after: right[i] });
    for (let i = shared; i < left.length; i++) out.push({ path: `${path}[${i}]`, type: 'removed', before: left[i] });
    return;
  }

  out.push({ path, type: 'changed', before: left, after: right });
}

/** Compare two JSON documents structurally. Both inputs are required. */
export function jsonDiff(leftRaw: string, rightRaw: string): JsonDiffResult {
  if (!leftRaw.trim() || !rightRaw.trim()) {
    return { changes: [], same: false, error: 'Both inputs are required' };
  }
  let left: Json;
  let right: Json;
  try {
    left = JSON.parse(leftRaw) as Json;
  } catch (e) {
    const msg = e instanceof Error ? e.message : 'Invalid JSON';
    return { changes: [], same: false, error: `Left: ${msg}` };
  }
  try {
    right = JSON.parse(rightRaw) as Json;
  } catch (e) {
    const msg = e instanceof Error ? e.message : 'Invalid JSON';
    return { changes: [], same: false, error: `Right: ${msg}` };
  }
  const changes: JsonDiffChange[] = [];
  walk(left, right, '$', changes);
  return { changes, same: changes.length === 0, 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 →