JSON Diff — Kotlin 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 Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-diff — structural JSON diff tool. Kotlin port (canonical TS:
// src/lib/json-diff.ts; Go twin: cli/json-diff). Hand-rolled strict JSON
// parser (no stdlib JSON parser exists in Kotlin) + 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, empty
// inputs as "Both inputs are required"; error is null exactly when the diff
// succeeded. Values keep their parsed form (LinkedHashMap / ArrayList /
// String / Double / Boolean / null).
data class JsonDiffChange(
/** "$"-rooted path: `$.name`, `$.users[0]`, `$[2]`. Root itself is `$`. */
val path: String,
/** "added" | "removed" | "changed" */
val type: String,
/** Left-side value. Null when type is "added". */
val before: Any? = null,
/** Right-side value. Null when type is "removed". */
val after: Any? = null,
)
data class JsonDiffResult(
val changes: List<JsonDiffChange>,
val same: Boolean,
/** null when the diff succeeded (TS: error: null). */
val error: String?,
)
class JsonDiffException(message: String) : Exception(message)
// ---- deep equality (JS === parity) ----
fun deepEqual(a: Any?, b: Any?): Boolean = when {
a is Double && b is Double -> a == b // 1 == 1.0, like JS ===
a is String && b is String -> a == b
a is Boolean && b is Boolean -> a == b
a is List<*> && b is List<*> ->
a.size == b.size && a.indices.all { deepEqual(a[it], b[it]) }
a is Map<*, *> && b is Map<*, *> ->
a.size == b.size &&
a.entries.all { (k, v) -> b.containsKey(k) && deepEqual(v, b[k]) }
else -> a == null && b == null // null === null; every other mix is false
}
// ---- structural walker ----
fun walk(l: Any?, r: Any?, path: String, out: MutableList<JsonDiffChange>) {
if (deepEqual(l, r)) return
if (l is Map<*, *> && r is Map<*, *>) {
val lm = l as Map<String, Any?>
val rm = r as Map<String, Any?>
// Sorted union of both key sets (key order never matters).
// String natural order = UTF-16 code-unit order, like JS sort.
for (key in (lm.keys + rm.keys).toSortedSet()) {
val child = "$path.$key"
when {
key !in lm -> out.add(JsonDiffChange(child, "added", after = rm[key]))
key !in rm -> out.add(JsonDiffChange(child, "removed", before = lm[key]))
else -> walk(lm[key], rm[key], child, out)
}
}
return
}
if (l is List<*> && r is List<*>) {
val shared = minOf(l.size, r.size)
for (i in 0 until shared) walk(l[i], r[i], "$path[$i]", out)
for (i in shared until r.size) out.add(JsonDiffChange("$path[$i]", "added", after = r[i]))
for (i in shared until l.size) out.add(JsonDiffChange("$path[$i]", "removed", before = l[i]))
return
}
out.add(JsonDiffChange(path, "changed", before = l, after = r))
}
// ---- recursive-descent parser mirroring JSON.parse ----
// Values map to LinkedHashMap<String, Any?> / ArrayList<Any?> / String /
// Double / Boolean / null; numbers parse as double (JS Number semantics);
// duplicate keys: last wins. Kotlin Char is a UTF-16 code unit.
class JsonParser(private val src: String) {
private var pos = 0
fun parse(): Any? {
skipWs()
val v = value()
skipWs()
if (pos != src.length) throw JsonDiffException("Invalid JSON: trailing content")
return v
}
private fun skipWs() {
while (pos < src.length && src[pos] in " \t\n\r") pos++
}
// NUL sentinel: never matches a real token, so it fails the parse.
private val nul: Char = 0.toChar()
private fun peek(): Char = if (pos < src.length) src[pos] else nul
private fun fail(msg: String): Nothing = throw JsonDiffException("Invalid JSON: $msg")
private fun value(): Any? = when (peek()) {
'{' -> parseObject()
'[' -> parseArray()
'"' -> parseString()
't' -> expect("true").let { true }
'f' -> expect("false").let { false }
'n' -> expect("null").let { null }
else -> parseNumber()
}
private fun expect(lit: String): String {
if (!src.startsWith(lit, pos)) fail("unexpected token")
pos += lit.length
return lit
}
private fun parseObject(): Map<String, Any?> {
pos++ // '{'
val out = LinkedHashMap<String, Any?>()
skipWs()
if (peek() == '}') { pos++; return out }
while (true) {
skipWs()
if (peek() != '"') fail("expected key")
val key = parseString()
skipWs()
if (peek() != ':') fail("expected ':'")
pos++
out[key] = value() // duplicate key: last wins
skipWs()
when (peek()) {
',' -> pos++
'}' -> { pos++; return out }
else -> fail("expected ',' or '}'")
}
}
}
private fun parseArray(): List<Any?> {
pos++ // '['
val out = ArrayList<Any?>()
skipWs()
if (peek() == ']') { pos++; return out }
while (true) {
out.add(value())
skipWs()
when (peek()) {
',' -> pos++
']' -> { pos++; return out }
else -> fail("expected ',' or ']'")
}
}
}
private fun parseString(): String {
pos++ // '"'
val out = StringBuilder()
while (pos < src.length && src[pos] != '"') {
val c = src[pos]
if (c == '\\') {
pos++
when (val e = peek()) {
'"' -> out.append('"')
'\\' -> out.append('\\')
'/' -> out.append('/')
'b' -> out.append('\b')
'f' -> out.append(0x0C.toChar())
'n' -> out.append('\n')
'r' -> out.append('\r')
't' -> out.append('\t')
'u' -> {
pos++ // 'u'
val cp = hex4()
if (Character.isHighSurrogate(cp) && pos + 1 < src.length &&
src[pos] == '\\' && src[pos + 1] == 'u'
) {
pos += 2 // now at the low surrogate's hex digits
val lo = hex4()
if (Character.isLowSurrogate(lo)) {
out.appendCodePoint(Character.toCodePoint(cp, lo))
} else fail("unmatched surrogate")
} else if (Character.isLowSurrogate(cp)) {
fail("unmatched surrogate")
} else {
out.append(cp)
}
}
else -> fail("bad escape")
}
pos++
} else {
if (c < ' ') fail("unescaped control character")
out.append(c) // raw UTF-16 passes through
pos++
}
}
if (peek() != '"') fail("unterminated string")
pos++
return out.toString()
}
/** Reads the 4 hex digits at pos and advances; surrogate pairs are
* combined by the caller. */
private fun hex4(): Char {
if (pos + 4 > src.length) fail("bad \\u escape")
var cp = 0
for (i in 0 until 4) {
val c = src[pos + i]
cp = cp shl 4
cp = when (c) {
in '0'..'9' -> cp or (c - '0')
in 'a'..'f' -> cp or (c - 'a' + 10)
in 'A'..'F' -> cp or (c - 'A' + 10)
else -> fail("bad \\u escape")
}
}
pos += 4
return cp.toChar()
}
/** Strict JSON number grammar (JSON.parse rejects "01", "1.", ".5",
* "+1"); toDouble overflow yields Infinity, like JS. */
private fun parseNumber(): Double {
var q = pos
if (q < src.length && src[q] == '-') q++
if (q < src.length && src[q] == '0') q++
else if (q < src.length && src[q] in '1'..'9') {
while (q < src.length && src[q].isDigit()) q++
} else fail("unexpected token")
if (q < src.length && src[q] == '.') {
q++
if (q >= src.length || !src[q].isDigit()) fail("bad number")
while (q < src.length && src[q].isDigit()) q++
}
if (q < src.length && (src[q] == 'e' || src[q] == 'E')) {
q++
if (q < src.length && (src[q] == '+' || src[q] == '-')) q++
if (q >= src.length || !src[q].isDigit()) fail("bad number")
while (q < src.length && src[q].isDigit()) q++
}
val literal = src.substring(pos, q)
pos = q
return literal.toDouble()
}
}
/** Compare two JSON documents structurally. Both inputs are required. */
fun jsonDiff(leftRaw: String, rightRaw: String): JsonDiffResult {
if (leftRaw.isBlank() || rightRaw.isBlank()) {
return JsonDiffResult(emptyList(), false, "Both inputs are required")
}
val left: Any?
try {
left = JsonParser(leftRaw).parse()
} catch (e: JsonDiffException) {
return JsonDiffResult(emptyList(), false, "Left: ${e.message}")
}
val right: Any?
try {
right = JsonParser(rightRaw).parse()
} catch (e: JsonDiffException) {
return JsonDiffResult(emptyList(), false, "Right: ${e.message}")
}
val changes = mutableListOf<JsonDiffChange>()
walk(left, right, "$", changes)
return JsonDiffResult(changes, changes.isEmpty(), null)
}
// Example:
// val r = jsonDiff("""{"name": "ada"}""", """{"name": "grace"}""")
// // r.same == false, r.error == null
// // r.changes[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 →