Skip to content

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

// json-diff — structural JSON diff tool. JavaScript port (canonical TS:
// src/lib/json-diff.ts; Go twin: cli/json-diff). Parses both documents, then
// walks them in parallel: objects recurse over the sorted union of both key
// sets (key order never matters), arrays recurse by shared index with NO LCS
// alignment — a shifted array reports every moved index as changed, by
// design. A type divergence (object → array, scalar → array, …) collapses
// into ONE change at the diverging path, never per-child; equality is deep
// and order-insensitive, so same:true means the documents are structurally
// identical. Never throws: parse failures travel as "Left: …" / "Right: …"
// strings and empty inputs as "Both inputs are required".
'use strict';

function jsonDiffIsObject(v) {
  return v !== null && typeof v === 'object' && !Array.isArray(v);
}

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

function jsonDiffWalk(left, right, path, out) {
  if (jsonDiffDeepEqual(left, right)) return;

  if (jsonDiffIsObject(left) && jsonDiffIsObject(right)) {
    const keys = [...new Set([...Object.keys(left), ...Object.keys(right)])].sort();
    for (const key of keys) {
      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 jsonDiffWalk(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++) jsonDiffWalk(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. */
function jsonDiff(leftRaw, rightRaw) {
  if (!leftRaw.trim() || !rightRaw.trim()) {
    return { changes: [], same: false, error: 'Both inputs are required' };
  }
  let left;
  let right;
  try {
    left = JSON.parse(leftRaw);
  } catch (e) {
    const msg = e instanceof Error ? e.message : 'Invalid JSON';
    return { changes: [], same: false, error: `Left: ${msg}` };
  }
  try {
    right = JSON.parse(rightRaw);
  } catch (e) {
    const msg = e instanceof Error ? e.message : 'Invalid JSON';
    return { changes: [], same: false, error: `Right: ${msg}` };
  }
  const changes = [];
  jsonDiffWalk(left, right, '$', changes);
  return { changes, same: changes.length === 0, error: null };
}

// Example:
// jsonDiff('{"name": "ada"}', '{"name": "grace"}').changes
// → [{ path: '$.name', type: 'changed', before: 'ada', after: 'grace' }]
// jsonDiff('[1, 2]', '[1, 2, 3]').changes
// → [{ path: '$[2]', type: 'added', after: 3 }]

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 →