JSON Diff — Zig 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 Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-diff — structural JSON diff tool. Zig port (canonical TS:
// src/lib/json-diff.ts; Go twin: cli/json-diff). Language: Zig 0.13 —
// std.json from the standard library (the Rust sibling embeds a hand-rolled
// parser, as Rust's stdlib has no JSON). Structural, not textual: walks both
// parsed documents and reports added/removed/changed values at "$"-rooted
// paths — 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 panics on malformed input: parse
// failures travel as the static strings "Left: Invalid JSON" /
// "Right: Invalid JSON" (std.json reports no message text), empty inputs as
// "Both inputs are required". All returned memory (changes, paths, and the
// parsed trees the changes reference) lives in the allocator you pass — use
// an ArenaAllocator and deinit it to free everything.
//
// Test: zig test zig.zig
const std = @import("std");
pub const Value = std.json.Value;
pub const ChangeKind = enum {
added,
removed,
changed,
pub fn asStr(self: ChangeKind) []const u8 {
return switch (self) {
.added => "added",
.removed => "removed",
.changed => "changed",
};
}
};
pub const Change = struct {
/// "$"-rooted path: `$.name`, `$.users[0]`, `$[2]`. Root itself is `$`.
path: []const u8,
kind: ChangeKind,
/// Left-side value. null when kind is .added.
before: ?Value = null,
/// Right-side value. null when kind is .removed.
after: ?Value = null,
};
pub const Result = struct {
changes: []Change = &[_]Change{},
same: bool = false,
/// null when the diff succeeded (TS: error: null).
err: ?[]const u8 = null,
};
fn strLess(_: void, a: []const u8, b: []const u8) bool {
return std.mem.order(u8, a, b) == .lt;
}
fn isBlank(s: []const u8) bool {
for (s) |c| {
if (!std.ascii.isWhitespace(c)) return false;
}
return true;
}
/// Numbers across all std.json variants as f64, so 1 == 1.0 like JS ===.
/// .number_string only appears when a literal overflows i64/f64.
fn numAsF64(v: Value) ?f64 {
return switch (v) {
.integer => |i| @floatFromInt(i),
.float => |f| f,
.number_string => |s| std.fmt.parseFloat(f64, s) catch null,
else => null,
};
}
/// Deep, order-insensitive equality (JS === parity: 1 == 1.0, true != 1).
fn deepEqual(a: Value, b: Value) bool {
const na = numAsF64(a);
const nb = numAsF64(b);
if (na != null or nb != null) {
// A number never equals a string/bool/array/object.
return na != null and nb != null and na.? == nb.?;
}
if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false;
switch (a) {
.null => return true,
.bool => return a.bool == b.bool,
.string => return std.mem.eql(u8, a.string, b.string),
.array => {
const xa = a.array.items;
const xb = b.array.items;
if (xa.len != xb.len) return false;
for (xa, xb) |ea, eb| {
if (!deepEqual(ea, eb)) return false;
}
return true;
},
.object => {
const xa = a.object;
const xb = b.object;
if (xa.count() != xb.count()) return false;
var it = xa.iterator();
while (it.next()) |e| {
const bv = xb.get(e.key_ptr.*) orelse return false;
if (!deepEqual(e.value_ptr.*, bv)) return false;
}
return true;
},
else => return false,
}
}
fn walk(a: std.mem.Allocator, l: Value, r: Value, path: []const u8, out: *std.ArrayList(Change)) std.mem.Allocator.Error!void {
if (deepEqual(l, r)) return;
if (std.meta.activeTag(l) == .object and std.meta.activeTag(r) == .object) {
// Sorted union of both key sets (key order never matters). Byte
// order = code point order; JS sort is UTF-16 code-unit order.
var keys = std.ArrayList([]const u8).init(a);
var seen = std.StringHashMap(void).init(a);
var lit = l.object.iterator();
while (lit.next()) |e| {
if (!seen.contains(e.key_ptr.*)) {
try seen.put(e.key_ptr.*, {});
try keys.append(e.key_ptr.*);
}
}
var rit = r.object.iterator();
while (rit.next()) |e| {
if (!seen.contains(e.key_ptr.*)) {
try seen.put(e.key_ptr.*, {});
try keys.append(e.key_ptr.*);
}
}
std.mem.sort([]const u8, keys.items, {}, strLess);
for (keys.items) |key| {
const child = try std.fmt.allocPrint(a, "{s}.{s}", .{ path, key });
const lv = l.object.get(key);
const rv = r.object.get(key);
if (lv == null and rv != null) {
try out.append(.{ .path = child, .kind = .added, .after = rv });
} else if (lv != null and rv == null) {
try out.append(.{ .path = child, .kind = .removed, .before = lv });
} else if (lv != null and rv != null) {
try walk(a, lv.?, rv.?, child, out);
}
}
return;
}
if (std.meta.activeTag(l) == .array and std.meta.activeTag(r) == .array) {
const la = l.array.items;
const ra = r.array.items;
const shared = @min(la.len, ra.len);
var i: usize = 0;
while (i < shared) : (i += 1) {
const child = try std.fmt.allocPrint(a, "{s}[{d}]", .{ path, i });
try walk(a, la[i], ra[i], child, out);
}
i = shared;
while (i < ra.len) : (i += 1) {
try out.append(.{
.path = try std.fmt.allocPrint(a, "{s}[{d}]", .{ path, i }),
.kind = .added,
.after = ra[i],
});
}
i = shared;
while (i < la.len) : (i += 1) {
try out.append(.{
.path = try std.fmt.allocPrint(a, "{s}[{d}]", .{ path, i }),
.kind = .removed,
.before = la[i],
});
}
return;
}
// A type divergence (object → array, scalar → array, …) collapses into
// ONE change at the diverging path, never per-child.
try out.append(.{ .path = path, .kind = .changed, .before = l, .after = r });
}
/// Compare two JSON documents structurally. Both inputs are required.
pub fn jsonDiff(a: std.mem.Allocator, left_raw: []const u8, right_raw: []const u8) Result {
if (isBlank(left_raw) or isBlank(right_raw)) {
return .{ .err = "Both inputs are required" };
}
const left = std.json.parseFromSliceLeaky(Value, a, left_raw, .{}) catch {
return .{ .err = "Left: Invalid JSON" };
};
const right = std.json.parseFromSliceLeaky(Value, a, right_raw, .{}) catch {
return .{ .err = "Right: Invalid JSON" };
};
var changes = std.ArrayList(Change).init(a);
walk(a, left, right, "$", &changes) catch {
return .{ .err = "Out of memory" };
};
return .{ .changes = changes.items, .same = changes.items.len == 0, .err = null };
}
pub fn main() !void {
// Small end-to-end demo so this file is runnable as a showcase.
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const res = jsonDiff(
arena.allocator(),
"{\"name\": \"ada\", \"old\": 1}",
"{\"name\": \"grace\", \"new\": [1, 2]}",
);
if (res.err) |e| {
std.debug.print("error: {s}\n", .{e});
return;
}
for (res.changes) |c| {
std.debug.print("{s} {s}\n", .{ c.kind.asStr(), c.path });
}
}
test "json_diff changed, added, removed in sorted key order" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const res = jsonDiff(
arena.allocator(),
"{\"name\": \"ada\", \"old\": 1}",
"{\"name\": \"grace\", \"new\": 2}",
);
try std.testing.expect(res.err == null);
try std.testing.expect(!res.same);
try std.testing.expectEqual(@as(usize, 3), res.changes.len);
try std.testing.expectEqualStrings("$.name", res.changes[0].path);
try std.testing.expectEqual(ChangeKind.changed, res.changes[0].kind);
try std.testing.expectEqualStrings("$.new", res.changes[1].path);
try std.testing.expectEqual(ChangeKind.added, res.changes[1].kind);
try std.testing.expectEqualStrings("$.old", res.changes[2].path);
try std.testing.expectEqual(ChangeKind.removed, res.changes[2].kind);
}
test "json_diff identical documents are same" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const res = jsonDiff(
arena.allocator(),
"{\"a\": [1, {\"b\": \"x\"}], \"c\": null}",
"{\"c\": null, \"a\": [1.0, {\"b\": \"x\"}]}",
);
try std.testing.expect(res.err == null);
try std.testing.expect(res.same);
try std.testing.expectEqual(@as(usize, 0), res.changes.len);
}
test "json_diff arrays recurse by index, tails become added or removed" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const res = jsonDiff(arena.allocator(), "[1, 2, 3]", "[1, 9, 3, 4]");
try std.testing.expect(res.err == null);
try std.testing.expect(!res.same);
try std.testing.expectEqual(@as(usize, 2), res.changes.len);
try std.testing.expectEqualStrings("$[1]", res.changes[0].path);
try std.testing.expectEqual(ChangeKind.changed, res.changes[0].kind);
try std.testing.expectEqualStrings("$[3]", res.changes[1].path);
try std.testing.expectEqual(ChangeKind.added, res.changes[1].kind);
}
test "json_diff type divergence collapses into one change" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const res = jsonDiff(arena.allocator(), "{\"a\": {\"b\": 1}}", "{\"a\": [1]}");
try std.testing.expect(res.err == null);
try std.testing.expectEqual(@as(usize, 1), res.changes.len);
try std.testing.expectEqualStrings("$.a", res.changes[0].path);
try std.testing.expectEqual(ChangeKind.changed, res.changes[0].kind);
}
test "json_diff input guards" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const empty = jsonDiff(a, "", "{}");
try std.testing.expectEqualStrings("Both inputs are required", empty.err.?);
try std.testing.expect(!empty.same);
const bad_left = jsonDiff(a, "{oops", "{}");
try std.testing.expectEqualStrings("Left: Invalid JSON", bad_left.err.?);
const bad_right = jsonDiff(a, "{}", "[");
try std.testing.expectEqualStrings("Right: Invalid JSON", bad_right.err.?);
}
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 →