Skip to content

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

// json-diff — structural JSON diff tool. C++ port (canonical TS:
// src/lib/json-diff.ts; Go twin: cli/json-diff). Hand-rolled strict JSON
// parser + structural walker (standard library only): 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". The result owns both parsed trees;
// changes' before/after point into them.
#include <algorithm>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
#include <vector>

namespace jsondiff {

enum class Kind { Null, Bool, Num, Str, Arr, Obj };

struct JsonValue;

using JsonMember = std::pair<std::string, JsonValue>;

struct JsonValue {
    Kind kind = Kind::Null;
    bool boolean = false;         // Kind::Bool
    double number = 0.0;          // Kind::Num
    std::string string;           // Kind::Str
    std::vector<JsonValue> items; // Kind::Arr
    std::vector<JsonMember> members; // Kind::Obj (insertion order preserved)
};

// ---- 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) ----

class Parser {
public:
    explicit Parser(const std::string &src) : src_(src.c_str()), pos_(0) {}

    std::unique_ptr<JsonValue> document() {
        auto v = value();
        if (!v) return nullptr;
        ws();
        if (src_[pos_] != '\0') { fail("Trailing characters"); return nullptr; }
        return v;
    }

    const std::string &error() const { return err_; }

private:
    const char *src_;
    std::size_t pos_ = 0;
    std::string err_;

    void fail(const char *msg) { if (err_.empty()) err_ = msg; }

    void ws() {
        while (src_[pos_] == ' ' || src_[pos_] == '\t' || src_[pos_] == '\n' || src_[pos_] == '\r') pos_++;
    }

    static bool digit(char c) { return c >= '0' && c <= '9'; }

    bool hex4(unsigned &out) {
        unsigned v = 0;
        for (int i = 0; i < 4; i++) {
            char c = src_[pos_];
            unsigned d;
            if (c >= '0' && c <= '9') d = static_cast<unsigned>(c - '0');
            else if (c >= 'a' && c <= 'f') d = static_cast<unsigned>(c - 'a') + 10;
            else if (c >= 'A' && c <= 'F') d = static_cast<unsigned>(c - 'A') + 10;
            else { fail("Bad \\u escape"); return false; }
            v = v * 16 + d;
            pos_++;
        }
        out = v;
        return true;
    }

    static void utf8(std::string &out, unsigned cp) {
        if (cp < 0x80) out.push_back(static_cast<char>(cp));
        else if (cp < 0x800) {
            out.push_back(static_cast<char>(0xC0 | (cp >> 6)));
            out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
        } else if (cp < 0x10000) {
            out.push_back(static_cast<char>(0xE0 | (cp >> 12)));
            out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
            out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
        } else {
            out.push_back(static_cast<char>(0xF0 | (cp >> 18)));
            out.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
            out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
            out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
        }
    }

    std::unique_ptr<JsonValue> str() {
        pos_++; // opening quote
        std::string out;
        for (;;) {
            char c = src_[pos_];
            if (c == '\0') { fail("Unterminated string"); return nullptr; }
            if (c == '"') { pos_++; break; }
            if (c == '\\') {
                pos_++;
                char e = src_[pos_];
                switch (e) {
                case '"': out.push_back('"'); pos_++; break;
                case '\\': out.push_back('\\'); pos_++; break;
                case '/': out.push_back('/'); pos_++; break;
                case 'b': out.push_back('\b'); pos_++; break;
                case 'f': out.push_back('\f'); pos_++; break;
                case 'n': out.push_back('\n'); pos_++; break;
                case 'r': out.push_back('\r'); pos_++; break;
                case 't': out.push_back('\t'); pos_++; break;
                case 'u': {
                    pos_++;
                    unsigned cp;
                    if (!hex4(cp)) return nullptr;
                    if (cp >= 0xD800 && cp <= 0xDBFF) {
                        if (src_[pos_] == '\\' && src_[pos_ + 1] == 'u') {
                            pos_ += 2;
                            unsigned lo;
                            if (!hex4(lo)) return nullptr;
                            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;
                    utf8(out, cp);
                    break;
                }
                default: fail("Bad escape"); return nullptr;
                }
            } else {
                out.push_back(c);
                pos_++;
            }
        }
        auto v = std::make_unique<JsonValue>();
        v->kind = Kind::Str;
        v->string = std::move(out);
        return v;
    }

    std::unique_ptr<JsonValue> number() {
        std::size_t start = pos_;
        const char *s = src_;
        if (s[pos_] == '-') pos_++;
        if (!digit(s[pos_])) { fail("Invalid number"); return nullptr; }
        if (s[pos_] == '0') pos_++;
        else while (digit(s[pos_])) pos_++;
        if (s[pos_] == '.') {
            pos_++;
            if (!digit(s[pos_])) { fail("Invalid number"); return nullptr; }
            while (digit(s[pos_])) pos_++;
        }
        if (s[pos_] == 'e' || s[pos_] == 'E') {
            pos_++;
            if (s[pos_] == '+' || s[pos_] == '-') pos_++;
            if (!digit(s[pos_])) { fail("Invalid number"); return nullptr; }
            while (digit(s[pos_])) pos_++;
        }
        const double d = std::strtod(std::string(s + start, pos_ - start).c_str(), nullptr);
        auto v = std::make_unique<JsonValue>();
        v->kind = Kind::Num;
        v->number = d;
        return v;
    }

    std::unique_ptr<JsonValue> array() {
        pos_++; // '['
        auto v = std::make_unique<JsonValue>();
        v->kind = Kind::Arr;
        ws();
        if (src_[pos_] == ']') { pos_++; return v; }
        for (;;) {
            auto el = value();
            if (!el) return nullptr;
            v->items.push_back(std::move(*el));
            ws();
            char c = src_[pos_];
            if (c == ',') { pos_++; ws(); continue; }
            if (c == ']') { pos_++; return v; }
            fail("Unexpected token");
            return nullptr;
        }
    }

    std::unique_ptr<JsonValue> object() {
        pos_++; // '{'
        auto v = std::make_unique<JsonValue>();
        v->kind = Kind::Obj;
        ws();
        if (src_[pos_] == '}') { pos_++; return v; }
        for (;;) {
            if (src_[pos_] != '"') { fail("Unexpected token"); return nullptr; }
            auto key = str();
            if (!key) return nullptr;
            ws();
            if (src_[pos_] != ':') { fail("Unexpected token"); return nullptr; }
            pos_++;
            ws();
            auto val = value();
            if (!val) return nullptr;
            // JSON objects keep the LAST value for a duplicate key (JSON.parse).
            bool replaced = false;
            for (auto &m : v->members) {
                if (m.first == key->string) { m.second = std::move(*val); replaced = true; break; }
            }
            if (!replaced) v->members.emplace_back(std::move(key->string), std::move(*val));
            ws();
            char c = src_[pos_];
            if (c == ',') { pos_++; ws(); continue; }
            if (c == '}') { pos_++; return v; }
            fail("Unexpected token");
            return nullptr;
        }
    }

    std::unique_ptr<JsonValue> value() {
        ws();
        char c = src_[pos_];
        if (c == '{') return object();
        if (c == '[') return array();
        if (c == '"') return str();
        if (c == 't' && std::strncmp(src_ + pos_, "true", 4) == 0) {
            pos_ += 4;
            auto v = std::make_unique<JsonValue>();
            v->kind = Kind::Bool;
            v->boolean = true;
            return v;
        }
        if (c == 'f' && std::strncmp(src_ + pos_, "false", 5) == 0) {
            pos_ += 5;
            auto v = std::make_unique<JsonValue>();
            v->kind = Kind::Bool;
            v->boolean = false;
            return v;
        }
        if (c == 'n' && std::strncmp(src_ + pos_, "null", 4) == 0) {
            pos_ += 4;
            return std::make_unique<JsonValue>(); // Kind::Null
        }
        if (digit(c) || c == '-') return number();
        fail("Unexpected token");
        return nullptr;
    }
};

// ---- structural diff (mirrors the TS walk) ----

const JsonValue *objGet(const JsonValue &o, const std::string &key) {
    for (const auto &m : o.members)
        if (m.first == key) return &m.second;
    return nullptr;
}

bool equal(const JsonValue &a, const JsonValue &b) {
    if (a.kind != b.kind) return false;
    switch (a.kind) {
    case Kind::Null: return true;
    case Kind::Bool: return a.boolean == b.boolean;
    case Kind::Num: return a.number == b.number; // 1 == 1.0, like JS ===
    case Kind::Str: return a.string == b.string;
    case Kind::Arr:
        if (a.items.size() != b.items.size()) return false;
        for (std::size_t i = 0; i < a.items.size(); i++)
            if (!equal(a.items[i], b.items[i])) return false;
        return true;
    case Kind::Obj:
        if (a.members.size() != b.members.size()) return false;
        for (const auto &m : a.members) {
            const JsonValue *bv = objGet(b, m.first);
            if (!bv || !equal(m.second, *bv)) return false;
        }
        return true;
    }
    return false;
}

struct Change {
    std::string path;            // "$"-rooted: $.name, $.users[0], $[2]
    std::string type;            // "added" | "removed" | "changed"
    const JsonValue *before = nullptr; // null when absent (added)
    const JsonValue *after = nullptr;  // null when absent (removed)
};

struct Result {
    std::unique_ptr<JsonValue> left;  // parsed left tree (changes point into it)
    std::unique_ptr<JsonValue> right; // parsed right tree
    std::vector<Change> changes;
    bool same = false;
    std::shared_ptr<std::string> error; // null when ok (TS: error: null)
};

void walk(const JsonValue &l, const JsonValue &r, const std::string &path, Result &res) {
    if (equal(l, r)) return;

    if (l.kind == Kind::Obj && r.kind == Kind::Obj) {
        std::vector<std::string> keys;
        keys.reserve(l.members.size() + r.members.size());
        for (const auto &m : l.members) keys.push_back(m.first);
        for (const auto &m : r.members) keys.push_back(m.first);
        std::sort(keys.begin(), keys.end());
        keys.erase(std::unique(keys.begin(), keys.end()), keys.end());
        for (const auto &key : keys) {
            const std::string child = path + "." + key;
            const JsonValue *lv = objGet(l, key);
            const JsonValue *rv = objGet(r, key);
            if (!lv) {
                Change c; c.path = child; c.type = "added"; c.after = rv;
                res.changes.push_back(std::move(c));
            } else if (!rv) {
                Change c; c.path = child; c.type = "removed"; c.before = lv;
                res.changes.push_back(std::move(c));
            } else {
                walk(*lv, *rv, child, res);
            }
        }
        return;
    }

    if (l.kind == Kind::Arr && r.kind == Kind::Arr) {
        const std::size_t shared = std::min(l.items.size(), r.items.size());
        for (std::size_t i = 0; i < shared; i++)
            walk(l.items[i], r.items[i], path + "[" + std::to_string(i) + "]", res);
        for (std::size_t i = shared; i < r.items.size(); i++) {
            Change c; c.path = path + "[" + std::to_string(i) + "]"; c.type = "added"; c.after = &r.items[i];
            res.changes.push_back(std::move(c));
        }
        for (std::size_t i = shared; i < l.items.size(); i++) {
            Change c; c.path = path + "[" + std::to_string(i) + "]"; c.type = "removed"; c.before = &l.items[i];
            res.changes.push_back(std::move(c));
        }
        return;
    }

    Change c; c.path = path; c.type = "changed"; c.before = &l; c.after = &r;
    res.changes.push_back(std::move(c));
}

bool blank(const std::string &s) {
    for (char c : s)
        if (c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != '\v' && c != '\f') return false;
    return true;
}

std::shared_ptr<std::string> sideError(const std::string &side, const std::string &msg) {
    return std::make_shared<std::string>(side + ": " + msg);
}

// Compare two JSON documents structurally. Both inputs are required.
Result jsonDiff(const std::string &leftRaw, const std::string &rightRaw) {
    Result res;
    if (blank(leftRaw) || blank(rightRaw)) {
        res.error = std::make_shared<std::string>("Both inputs are required");
        return res;
    }
    Parser lp(leftRaw);
    res.left = lp.document();
    if (!res.left) {
        res.error = sideError("Left", lp.error().empty() ? "Invalid JSON" : lp.error());
        return res;
    }
    Parser rp(rightRaw);
    res.right = rp.document();
    if (!res.right) {
        res.error = sideError("Right", rp.error().empty() ? "Invalid JSON" : rp.error());
        res.left = nullptr;
        return res;
    }
    walk(*res.left, *res.right, "$", res);
    res.same = res.changes.empty();
    return res;
}

} // namespace jsondiff

// Example:
//   auto r = jsondiff::jsonDiff(R"({"name": "ada"})", R"({"name": "grace"})");
//   if (!r.error) {
//     // r.same == false; r.changes[0]: path "$.name" type "changed"
//     //                       before "ada" after "grace"
//   }
//   // changes[].before/after point into r.left/r.right — keep those alive.

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 →