Skip to content

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

// json-diff — structural JSON diff tool. Swift port (canonical TS:
// src/lib/json-diff.ts; Go twin: cli/json-diff). Hand-rolled strict JSON
// parser + structural walker (Swift standard library only, no Foundation):
// 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 traps on malformed input: parse
// failures travel as "Left: …" / "Right: …" strings in result.error (nil
// when ok), empty inputs as "Both inputs are required".

indirect enum JsonValue {
    case null
    case bool(Bool)
    case number(Double)
    case string(String)
    case array([JsonValue])
    case object([(String, JsonValue)]) // insertion order preserved; duplicate key keeps last
}

extension JsonValue: Equatable {
    static func == (l: JsonValue, r: JsonValue) -> Bool {
        switch (l, r) {
        case (.null, .null):
            return true
        case (.bool(let a), .bool(let b)):
            return a == b
        case (.number(let a), .number(let b)):
            return a == b // 1 == 1.0, like JS ===
        case (.string(let a), .string(let b)):
            return a == b
        case (.array(let a), .array(let b)):
            if a.count != b.count { return false }
            for i in 0..<a.count where !(a[i] == b[i]) { return false }
            return true
        case (.object(let a), .object(let b)):
            if a.count != b.count { return false }
            for (k, v) in a {
                guard let bv = b.first(where: { $0.0 == k })?.1, bv == v else { return false }
            }
            return true
        default:
            return false
        }
    }
}

struct JsonParseError: Error {
    let message: String
}

struct JsonParser {
    let src: [UInt8]
    var pos = 0

    init(_ s: String) {
        src = Array(s.utf8)
    }

    static func digit(_ c: UInt8) -> Bool {
        c >= 0x30 && c <= 0x39
    }

    mutating func fail<T>(_ message: String) throws -> T {
        throw JsonParseError(message: message)
    }

    mutating func ws() {
        while pos < src.count && (src[pos] == 0x20 || src[pos] == 0x09 || src[pos] == 0x0A || src[pos] == 0x0D) {
            pos += 1
        }
    }

    mutating func hex4() throws -> UInt32 {
        var v: UInt32 = 0
        for _ in 0..<4 {
            guard pos < src.count else { return try fail("Bad \\u escape") }
            let c = src[pos]
            let d: UInt32
            switch c {
            case 0x30...0x39: d = UInt32(c - 0x30)
            case 0x61...0x66: d = UInt32(c - 0x61) + 10
            case 0x41...0x46: d = UInt32(c - 0x41) + 10
            default: return try fail("Bad \\u escape")
            }
            v = v * 16 + d
            pos += 1
        }
        return v
    }

    static func utf8Push(_ out: inout [UInt8], _ cp: UInt32) {
        if cp < 0x80 {
            out.append(UInt8(cp))
        } else if cp < 0x800 {
            out.append(UInt8(0xC0 | (cp >> 6)))
            out.append(UInt8(0x80 | (cp & 0x3F)))
        } else if cp < 0x10000 {
            out.append(UInt8(0xE0 | (cp >> 12)))
            out.append(UInt8(0x80 | ((cp >> 6) & 0x3F)))
            out.append(UInt8(0x80 | (cp & 0x3F)))
        } else {
            out.append(UInt8(0xF0 | (cp >> 18)))
            out.append(UInt8(0x80 | ((cp >> 12) & 0x3F)))
            out.append(UInt8(0x80 | ((cp >> 6) & 0x3F)))
            out.append(UInt8(0x80 | (cp & 0x3F)))
        }
    }

    mutating func string() throws -> String {
        pos += 1 // opening quote
        var out: [UInt8] = []
        while true {
            guard pos < src.count else { return try fail("Unterminated string") }
            let c = src[pos]
            if c == 0x22 { // '"'
                pos += 1
                break
            }
            if c == 0x5C { // '\\'
                pos += 1
                guard pos < src.count else { return try fail("Unterminated string") }
                let e = src[pos]
                switch e {
                case 0x22: out.append(0x22)
                case 0x5C: out.append(0x5C)
                case 0x2F: out.append(0x2F)
                case 0x62: out.append(0x08)
                case 0x66: out.append(0x0C)
                case 0x6E: out.append(0x0A)
                case 0x72: out.append(0x0D)
                case 0x74: out.append(0x09)
                case 0x75: // 'u'
                    pos += 1
                    var cp = try hex4()
                    if cp >= 0xD800 && cp <= 0xDBFF {
                        if pos + 1 < src.count && src[pos] == 0x5C && src[pos + 1] == 0x75 {
                            pos += 2
                            let lo = try hex4()
                            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
                    }
                    Self.utf8Push(&out, cp)
                    continue
                default:
                    return try fail("Bad escape")
                }
                pos += 1
            } else {
                out.append(c)
                pos += 1
            }
        }
        return String(decoding: out, as: UTF8.self)
    }

    mutating func number() throws -> JsonValue {
        let start = pos
        if pos < src.count && src[pos] == 0x2D { pos += 1 } // '-'
        guard pos < src.count && Self.digit(src[pos]) else { return try fail("Invalid number") }
        if src[pos] == 0x30 { // '0'
            pos += 1
        } else {
            while pos < src.count && Self.digit(src[pos]) { pos += 1 }
        }
        if pos < src.count && src[pos] == 0x2E { // '.'
            pos += 1
            guard pos < src.count && Self.digit(src[pos]) else { return try fail("Invalid number") }
            while pos < src.count && Self.digit(src[pos]) { pos += 1 }
        }
        if pos < src.count && (src[pos] == 0x65 || src[pos] == 0x45) { // 'e' 'E'
            pos += 1
            if pos < src.count && (src[pos] == 0x2B || src[pos] == 0x2D) { pos += 1 }
            guard pos < src.count && Self.digit(src[pos]) else { return try fail("Invalid number") }
            while pos < src.count && Self.digit(src[pos]) { pos += 1 }
        }
        let text = String(decoding: src[start..<pos], as: UTF8.self)
        guard let d = Double(text) else { return try fail("Invalid number") }
        return .number(d)
    }

    mutating func array() throws -> JsonValue {
        pos += 1 // '['
        var items: [JsonValue] = []
        ws()
        if pos < src.count && src[pos] == 0x5D { // ']'
            pos += 1
            return .array(items)
        }
        while true {
            let el = try value()
            items.append(el)
            ws()
            guard pos < src.count else { return try fail("Unexpected token") }
            let c = src[pos]
            if c == 0x2C { // ','
                pos += 1
                ws()
            } else if c == 0x5D { // ']'
                pos += 1
                return .array(items)
            } else {
                return try fail("Unexpected token")
            }
        }
    }

    mutating func object() throws -> JsonValue {
        pos += 1 // '{'
        var members: [(String, JsonValue)] = []
        ws()
        if pos < src.count && src[pos] == 0x7D { // '}'
            pos += 1
            return .object(members)
        }
        while true {
            guard pos < src.count && src[pos] == 0x22 else { return try fail("Unexpected token") }
            let key = try string()
            ws()
            guard pos < src.count && src[pos] == 0x3A else { return try fail("Unexpected token") } // ':'
            pos += 1
            ws()
            let val = try value()
            // JSON objects keep the LAST value for a duplicate key (JSON.parse).
            if let idx = members.firstIndex(where: { $0.0 == key }) {
                members[idx].1 = val
            } else {
                members.append((key, val))
            }
            ws()
            guard pos < src.count else { return try fail("Unexpected token") }
            let c = src[pos]
            if c == 0x2C { // ','
                pos += 1
                ws()
            } else if c == 0x7D { // '}'
                pos += 1
                return .object(members)
            } else {
                return try fail("Unexpected token")
            }
        }
    }

    mutating func value() throws -> JsonValue {
        ws()
        guard pos < src.count else { return try fail("Unexpected token") }
        let c = src[pos]
        switch c {
        case 0x7B: return try object()   // '{'
        case 0x5B: return try array()    // '['
        case 0x22: return .string(try string())
        case 0x74: // 't'
            guard src[pos...].starts(with: [0x74, 0x72, 0x75, 0x65]) else { return try fail("Unexpected token") }
            pos += 4
            return .bool(true)
        case 0x66: // 'f'
            guard src[pos...].starts(with: [0x66, 0x61, 0x6C, 0x73, 0x65]) else { return try fail("Unexpected token") }
            pos += 5
            return .bool(false)
        case 0x6E: // 'n'
            guard src[pos...].starts(with: [0x6E, 0x75, 0x6C, 0x6C]) else { return try fail("Unexpected token") }
            pos += 4
            return .null
        case 0x30...0x39, 0x2D:
            return try number()
        default:
            return try fail("Unexpected token")
        }
    }

    mutating func document() throws -> JsonValue {
        let v = try value()
        ws()
        if pos != src.count { return try fail("Trailing characters") }
        return v
    }
}

struct JsonDiffChange {
    /// "$"-rooted path: `$.name`, `$.users[0]`, `$[2]`. Root itself is `$`.
    let path: String
    /// "added" | "removed" | "changed"
    let type: String
    /// Left-side value. nil when type is "added".
    var before: JsonValue?
    /// Right-side value. nil when type is "removed".
    var after: JsonValue?
}

struct JsonDiffResult {
    var changes: [JsonDiffChange]
    var same: Bool
    /// nil when the diff succeeded (TS: error: null).
    var error: String?
}

func jsonDiffObjGet(_ o: JsonValue, _ key: String) -> JsonValue? {
    if case .object(let members) = o {
        return members.first(where: { $0.0 == key })?.1
    }
    return nil
}

func jsonDiffEqual(_ l: JsonValue, _ r: JsonValue) -> Bool {
    l == r
}

func jsonDiffWalk(_ l: JsonValue, _ r: JsonValue, _ path: String, _ out: inout [JsonDiffChange]) {
    if jsonDiffEqual(l, r) { return }

    if case .object(let lm) = l, case .object(let rm) = r {
        let keys = Array(Set(lm.map { $0.0 } + rm.map { $0.0 })).sorted()
        for key in keys {
            let child = "\(path).\(key)"
            let lv = jsonDiffObjGet(l, key)
            let rv = jsonDiffObjGet(r, key)
            switch (lv, rv) {
            case (nil, .some(let rv)):
                out.append(JsonDiffChange(path: child, type: "added", before: nil, after: rv))
            case (.some(let lv), nil):
                out.append(JsonDiffChange(path: child, type: "removed", before: lv, after: nil))
            case (.some(let lv), .some(let rv)):
                jsonDiffWalk(lv, rv, child, &out)
            default:
                break
            }
        }
        return
    }

    if case .array(let la) = l, case .array(let ra) = r {
        let shared = min(la.count, ra.count)
        for i in 0..<shared {
            jsonDiffWalk(la[i], ra[i], "\(path)[\(i)]", &out)
        }
        for i in shared..<ra.count {
            out.append(JsonDiffChange(path: "\(path)[\(i)]", type: "added", before: nil, after: ra[i]))
        }
        for i in shared..<la.count {
            out.append(JsonDiffChange(path: "\(path)[\(i)]", type: "removed", before: la[i], after: nil))
        }
        return
    }

    out.append(JsonDiffChange(path: path, type: "changed", before: l, after: r))
}

func jsonDiffBlank(_ s: String) -> Bool {
    s.allSatisfy { c in
        c == " " || c == "\t" || c == "\n" || c == "\r" || c == "\u{0B}" || c == "\u{0C}"
    }
}

/// Compare two JSON documents structurally. Both inputs are required.
func jsonDiff(_ leftRaw: String, _ rightRaw: String) -> JsonDiffResult {
    if jsonDiffBlank(leftRaw) || jsonDiffBlank(rightRaw) {
        return JsonDiffResult(changes: [], same: false, error: "Both inputs are required")
    }
    var lp = JsonParser(leftRaw)
    let left: JsonValue
    do {
        left = try lp.document()
    } catch let e as JsonParseError {
        return JsonDiffResult(changes: [], same: false, error: "Left: \(e.message)")
    } catch {
        return JsonDiffResult(changes: [], same: false, error: "Left: Invalid JSON")
    }
    var rp = JsonParser(rightRaw)
    let right: JsonValue
    do {
        right = try rp.document()
    } catch let e as JsonParseError {
        return JsonDiffResult(changes: [], same: false, error: "Right: \(e.message)")
    } catch {
        return JsonDiffResult(changes: [], same: false, error: "Right: Invalid JSON")
    }
    var changes: [JsonDiffChange] = []
    jsonDiffWalk(left, right, "$", &changes)
    return JsonDiffResult(changes: changes, same: changes.isEmpty, error: nil)
}

// Example:
// let r = jsonDiff(#"{"name": "ada"}"#, #"{"name": "grace"}"#)
// // r.same == false, r.error == nil
// // 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 →