JSON Diff — Java 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 Java implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-diff — structural JSON diff tool. Java port (canonical TS:
// src/lib/json-diff.ts; Go twin: cli/json-diff). Hand-rolled strict JSON
// parser (java.util only, code-point based so astral chars survive) +
// structural walker: objects recurse over the sorted union of both key sets
// (key order never matters), arrays by shared index with no LCS alignment —
// a shifted array reports every moved index as changed, by design. A type
// divergence collapses into ONE change at the diverging path; equality is
// deep and order-insensitive, so same == true means the documents are
// structurally identical (1 == 1.0, true != 1). Never throws on malformed
// input: parse failures travel as "Left: …" / "Right: …" strings in
// Result.error (null when ok), empty inputs as "Both inputs are required".
// Package-private: display snippets keep the repo filename (json-diff.java).
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
final class JsonDiff {
static final int K_NULL = 0, K_BOOL = 1, K_NUM = 2, K_STR = 3, K_ARR = 4, K_OBJ = 5;
static final class JVal {
final int kind;
boolean bool;
double num;
String str;
final List<JVal> arr = new ArrayList<>();
// insertion order preserved; duplicate key keeps last (JSON.parse)
final LinkedHashMap<String, JVal> obj = new LinkedHashMap<>();
JVal(int kind) {
this.kind = kind;
}
}
// ---- strict JSON parser (mirrors JSON.parse: rejects trailing garbage,
// leading-zero numbers and bare NaN/Infinity; lone \u surrogates decode
// to U+FFFD exactly like JSON.parse) ----
static final class JParser {
private final int[] src; // code points — astral chars stay single tokens
private int pos;
private String err;
JParser(String s) {
this.src = s.codePoints().toArray();
}
String error() {
return err == null ? "Invalid JSON" : err;
}
private void fail(String msg) {
if (err == null) err = msg;
}
private void ws() {
while (pos < src.length) {
int c = src[pos];
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') pos++;
else break;
}
}
private static boolean digit(int c) {
return c >= '0' && c <= '9';
}
private int hex4() {
int v = 0;
for (int i = 0; i < 4; i++) {
if (pos >= src.length) {
fail("Bad \\u escape");
return -1;
}
int c = src[pos];
int d;
if (c >= '0' && c <= '9') d = c - '0';
else if (c >= 'a' && c <= 'f') d = c - 'a' + 10;
else if (c >= 'A' && c <= 'F') d = c - 'A' + 10;
else {
fail("Bad \\u escape");
return -1;
}
v = v * 16 + d;
pos++;
}
return v;
}
private JVal string() {
pos++; // opening quote
StringBuilder sb = new StringBuilder();
while (true) {
if (pos >= src.length) {
fail("Unterminated string");
return null;
}
int c = src[pos];
if (c == '"') {
pos++;
break;
}
if (c == '\\') {
pos++;
if (pos >= src.length) {
fail("Unterminated string");
return null;
}
int e = src[pos];
if (e == '"') { sb.append('"'); pos++; }
else if (e == '\\') { sb.append('\\'); pos++; }
else if (e == '/') { sb.append('/'); pos++; }
else if (e == 'b') { sb.append('\b'); pos++; }
else if (e == 'f') { sb.append('\f'); pos++; }
else if (e == 'n') { sb.append('\n'); pos++; }
else if (e == 'r') { sb.append('\r'); pos++; }
else if (e == 't') { sb.append('\t'); pos++; }
else if (e == 'u') {
pos++;
int cp = hex4();
if (cp < 0) return null;
if (cp >= 0xD800 && cp <= 0xDBFF) {
if (pos + 1 < src.length && src[pos] == '\\' && src[pos + 1] == 'u') {
pos += 2;
int lo = hex4();
if (lo < 0) return null;
if (lo >= 0xDC00 && lo <= 0xDFFF)
cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
else {
cp = 0xFFFD;
pos -= 2; // second \u handled next round
}
} else {
cp = 0xFFFD;
}
} else if (cp >= 0xDC00 && cp <= 0xDFFF) {
cp = 0xFFFD;
}
sb.appendCodePoint(cp);
} else {
fail("Bad escape");
return null;
}
} else {
sb.appendCodePoint(c);
pos++;
}
}
JVal v = new JVal(K_STR);
v.str = sb.toString();
return v;
}
private JVal number() {
int start = pos;
if (src[pos] == '-') pos++;
if (pos >= src.length || !digit(src[pos])) {
fail("Invalid number");
return null;
}
if (src[pos] == '0') pos++;
else while (pos < src.length && digit(src[pos])) pos++;
if (pos < src.length && src[pos] == '.') {
pos++;
if (pos >= src.length || !digit(src[pos])) {
fail("Invalid number");
return null;
}
while (pos < src.length && digit(src[pos])) pos++;
}
if (pos < src.length && (src[pos] == 'e' || src[pos] == 'E')) {
pos++;
if (pos < src.length && (src[pos] == '+' || src[pos] == '-')) pos++;
if (pos >= src.length || !digit(src[pos])) {
fail("Invalid number");
return null;
}
while (pos < src.length && digit(src[pos])) pos++;
}
// Grammar-validated above; Double.parseDouble accepts the slice.
double d = Double.parseDouble(new String(src, start, pos - start));
JVal v = new JVal(K_NUM);
v.num = d;
return v;
}
private boolean startsWith(String kw) {
if (pos + kw.length() > src.length) return false;
for (int i = 0; i < kw.length(); i++)
if (src[pos + i] != kw.charAt(i)) return false;
return true;
}
private JVal value() {
ws();
if (pos >= src.length) {
fail("Unexpected token");
return null;
}
int c = src[pos];
switch (c) {
case '{':
return object();
case '[':
return array();
case '"':
return string();
case 't':
if (startsWith("true")) {
pos += 4;
JVal v = new JVal(K_BOOL);
v.bool = true;
return v;
}
fail("Unexpected token");
return null;
case 'f':
if (startsWith("false")) {
pos += 5;
return new JVal(K_BOOL);
}
fail("Unexpected token");
return null;
case 'n':
if (startsWith("null")) {
pos += 4;
return new JVal(K_NULL);
}
fail("Unexpected token");
return null;
default:
if (digit(c) || c == '-') return number();
fail("Unexpected token");
return null;
}
}
private JVal array() {
pos++; // '['
JVal v = new JVal(K_ARR);
ws();
if (pos < src.length && src[pos] == ']') {
pos++;
return v;
}
while (true) {
JVal el = value();
if (el == null) return null;
v.arr.add(el);
ws();
if (pos >= src.length) {
fail("Unexpected token");
return null;
}
int c = src[pos];
if (c == ',') {
pos++;
ws();
} else if (c == ']') {
pos++;
return v;
} else {
fail("Unexpected token");
return null;
}
}
}
private JVal object() {
pos++; // '{'
JVal v = new JVal(K_OBJ);
ws();
if (pos < src.length && src[pos] == '}') {
pos++;
return v;
}
while (true) {
if (pos >= src.length || src[pos] != '"') {
fail("Unexpected token");
return null;
}
JVal key = string();
if (key == null) return null;
ws();
if (pos >= src.length || src[pos] != ':') {
fail("Unexpected token");
return null;
}
pos++;
ws();
JVal val = value();
if (val == null) return null;
v.obj.put(key.str, val); // duplicate key keeps last
ws();
if (pos >= src.length) {
fail("Unexpected token");
return null;
}
int c = src[pos];
if (c == ',') {
pos++;
ws();
} else if (c == '}') {
pos++;
return v;
} else {
fail("Unexpected token");
return null;
}
}
}
JVal document() {
JVal v = value();
if (v == null) return null;
ws();
if (pos != src.length) {
fail("Trailing characters");
return null;
}
return v;
}
}
// ---- structural diff (mirrors the TS walk) ----
static final class Change {
/** "$"-rooted path: $.name, $.users[0], $[2]. Root itself is "$". */
final String path;
/** "added" | "removed" | "changed" */
final String type;
/** Left-side value. null when type is "added". */
JVal before;
/** Right-side value. null when type is "removed". */
JVal after;
Change(String path, String type) {
this.path = path;
this.type = type;
}
}
static final class Result {
final List<Change> changes = new ArrayList<>();
boolean same;
/** null when the diff succeeded (TS: error: null). */
String error;
}
private static boolean equal(JVal a, JVal b) {
if (a.kind != b.kind) return false;
switch (a.kind) {
case K_NULL:
return true;
case K_BOOL:
return a.bool == b.bool;
case K_NUM:
return a.num == b.num; // 1 == 1.0, like JS ===
case K_STR:
return a.str.equals(b.str);
case K_ARR:
if (a.arr.size() != b.arr.size()) return false;
for (int i = 0; i < a.arr.size(); i++)
if (!equal(a.arr.get(i), b.arr.get(i))) return false;
return true;
case K_OBJ:
if (a.obj.size() != b.obj.size()) return false;
for (Map.Entry<String, JVal> en : a.obj.entrySet()) {
JVal bv = b.obj.get(en.getKey());
if (bv == null || !equal(en.getValue(), bv)) return false;
}
return true;
default:
return false;
}
}
private static void walk(JVal l, JVal r, String path, Result res) {
if (equal(l, r)) return;
if (l.kind == K_OBJ && r.kind == K_OBJ) {
Set<String> union = new LinkedHashSet<>();
union.addAll(l.obj.keySet());
union.addAll(r.obj.keySet());
List<String> keys = new ArrayList<>(union);
Collections.sort(keys); // natural String order = UTF-16 code units, like JS .sort()
for (String key : keys) {
String child = path + "." + key;
JVal lv = l.obj.get(key);
JVal rv = r.obj.get(key);
if (lv == null) {
Change c = new Change(child, "added");
c.after = rv;
res.changes.add(c);
} else if (rv == null) {
Change c = new Change(child, "removed");
c.before = lv;
res.changes.add(c);
} else {
walk(lv, rv, child, res);
}
}
return;
}
if (l.kind == K_ARR && r.kind == K_ARR) {
int shared = Math.min(l.arr.size(), r.arr.size());
for (int i = 0; i < shared; i++) walk(l.arr.get(i), r.arr.get(i), path + "[" + i + "]", res);
for (int i = shared; i < r.arr.size(); i++) {
Change c = new Change(path + "[" + i + "]", "added");
c.after = r.arr.get(i);
res.changes.add(c);
}
for (int i = shared; i < l.arr.size(); i++) {
Change c = new Change(path + "[" + i + "]", "removed");
c.before = l.arr.get(i);
res.changes.add(c);
}
return;
}
Change c = new Change(path, "changed");
c.before = l;
c.after = r;
res.changes.add(c);
}
private static boolean blank(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != 0x0B && c != 0x0C) return false;
}
return true;
}
/** Compare two JSON documents structurally. Both inputs are required. */
static Result jsonDiff(String leftRaw, String rightRaw) {
Result res = new Result();
if (blank(leftRaw) || blank(rightRaw)) {
res.error = "Both inputs are required";
return res;
}
JParser lp = new JParser(leftRaw);
JVal left = lp.document();
if (left == null) {
res.error = "Left: " + lp.error();
return res;
}
JParser rp = new JParser(rightRaw);
JVal right = rp.document();
if (right == null) {
res.error = "Right: " + rp.error();
return res;
}
walk(left, right, "$", res);
res.same = res.changes.isEmpty();
return res;
}
// Example:
// Result r = JsonDiff.jsonDiff("{\"name\": \"ada\"}", "{\"name\": \"grace\"}");
// // r.same == false, r.error == null
// // r.changes.get(0): path "$.name" type "changed" before "ada" after "grace"
}
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 →