JSON Diff — Python 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 Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""json-diff — structural JSON diff tool. Python 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 raises — errors travel in the result dict: "Left: …" /
"Right: …" for parse failures, "Both inputs are required" for empty input.
"""
import json
def _reject_constant(_name):
"""NaN/Infinity are not valid JSON (JSON.parse rejects them too)."""
raise ValueError("invalid JSON constant")
def json_equal(a, b):
"""Mirror the TS deepEqual: scalars by strict equality, arrays
element-wise, objects by key set regardless of order. Booleans never
equal numbers — the guard below avoids Python's True == 1 trap."""
if isinstance(a, bool) or isinstance(b, bool):
return isinstance(a, bool) and isinstance(b, bool) and a is b
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return a == b # 1 == 1.0, exactly like JS === on numbers
if isinstance(a, list) and isinstance(b, list):
return len(a) == len(b) and all(json_equal(x, y) for x, y in zip(a, b))
if isinstance(a, dict) and isinstance(b, dict):
return a.keys() == b.keys() and all(json_equal(v, b[k]) for k, v in a.items())
if isinstance(a, str) and isinstance(b, str):
return a == b
return a is None and b is None
def _walk(left, right, path, out):
if json_equal(left, right):
return
if isinstance(left, dict) and isinstance(right, dict):
for key in sorted(set(left) | set(right)):
child = f"{path}.{key}"
if key not in left:
out.append({"path": child, "type": "added", "after": right[key]})
elif key not in right:
out.append({"path": child, "type": "removed", "before": left[key]})
else:
_walk(left[key], right[key], child, out)
return
if isinstance(left, list) and isinstance(right, list):
shared = min(len(left), len(right))
for i in range(shared):
_walk(left[i], right[i], f"{path}[{i}]", out)
for i in range(shared, len(right)):
out.append({"path": f"{path}[{i}]", "type": "added", "after": right[i]})
for i in range(shared, len(left)):
out.append({"path": f"{path}[{i}]", "type": "removed", "before": left[i]})
return
out.append({"path": path, "type": "changed", "before": left, "after": right})
def json_diff(left_raw, right_raw):
"""Compare two JSON documents structurally. Both inputs are required."""
if not left_raw.strip() or not right_raw.strip():
return {"changes": [], "same": False, "error": "Both inputs are required"}
try:
left = json.loads(left_raw, parse_constant=_reject_constant)
except ValueError as e:
return {"changes": [], "same": False, "error": f"Left: {e}"}
try:
right = json.loads(right_raw, parse_constant=_reject_constant)
except ValueError as e:
return {"changes": [], "same": False, "error": f"Right: {e}"}
changes = []
_walk(left, right, "$", changes)
return {"changes": changes, "same": len(changes) == 0, "error": None}
# Example:
# json_diff('{"name": "ada"}', '{"name": "grace"}')["changes"]
# → [{"path": "$.name", "type": "changed", "before": "ada", "after": "grace"}]
# json_diff("[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 →