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). System.Text.Json parses
// both documents (like the json-to-schema sibling); the diff itself is a
// 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. Before/After carry the value's raw JSON
// text (GetRawText()), so results stay valid after the documents dispose.
using System;
using System.Collections.Generic;
using System.Text.Json;
public sealed class JsonDiffChange
{
/// "$"-rooted path: `$.name`, `$.users[0]`, `$[2]`. Root itself is `$`.
public string Path { get; set; } = "$";
/// "added" | "removed" | "changed"
public string Type { get; set; } = "changed";
/// Left-side value as raw JSON text. Null when Type is "added".
public string Before { get; set; }
/// Right-side value as raw JSON text. Null when Type is "removed".
public string After { get; set; }
}
public sealed class JsonDiffResult
{
public List<JsonDiffChange> Changes { get; } = new List<JsonDiffChange>();
/// True when the documents are structurally identical.
public bool Same { get; set; }
/// Null when the diff succeeded (TS: error: null).
public string Error { get; set; }
}
public static class JsonDiff
{
/// Compare two JSON documents structurally. Both inputs are required.
public static JsonDiffResult Diff(string leftRaw, string rightRaw)
{
var res = new JsonDiffResult();
if (string.IsNullOrWhiteSpace(leftRaw) || string.IsNullOrWhiteSpace(rightRaw))
{
res.Error = "Both inputs are required";
return res;
}
JsonDocument leftDoc = null;
JsonDocument rightDoc = null;
try
{
try
{
leftDoc = JsonDocument.Parse(leftRaw, new JsonDocumentOptions
{
MaxDepth = 1024, // far past JSON.parse's practical stack limit
});
}
catch (JsonException e)
{
res.Error = "Left: " + e.Message;
return res;
}
try
{
rightDoc = JsonDocument.Parse(rightRaw, new JsonDocumentOptions
{
MaxDepth = 1024,
});
}
catch (JsonException e)
{
res.Error = "Right: " + e.Message;
return res;
}
Walk(leftDoc.RootElement, rightDoc.RootElement, "$", res.Changes);
res.Same = res.Changes.Count == 0;
return res;
}
finally
{
leftDoc?.Dispose();
rightDoc?.Dispose();
}
}
// ---- deep equality (JS === parity) ----
private static bool DeepEqual(JsonElement a, JsonElement b)
{
if (a.ValueKind == JsonValueKind.Number && b.ValueKind == JsonValueKind.Number)
{
return a.GetDouble() == b.GetDouble(); // 1 == 1.0, like JS ===
}
if (a.ValueKind != b.ValueKind) return false;
switch (a.ValueKind)
{
case JsonValueKind.Null:
return true;
case JsonValueKind.True:
case JsonValueKind.False:
return true; // same kind ⇒ same boolean
case JsonValueKind.String:
return a.GetString() == b.GetString(); // ordinal, like JS ===
case JsonValueKind.Array:
if (a.GetArrayLength() != b.GetArrayLength()) return false;
var bi = b.EnumerateArray().GetEnumerator();
foreach (var ea in a.EnumerateArray())
{
bi.MoveNext();
if (!DeepEqual(ea, bi.Current)) return false;
}
return true;
case JsonValueKind.Object:
int count = 0;
foreach (var p in a.EnumerateObject())
{
count++;
if (!b.TryGetProperty(p.Name, out JsonElement bv)) return false;
if (!DeepEqual(p.Value, bv)) return false;
}
int bCount = 0;
foreach (var _ in b.EnumerateObject()) bCount++;
return count == bCount;
default:
return false;
}
}
// ---- structural walker ----
private static string RawText(JsonElement v) => v.GetRawText();
private static void Walk(JsonElement left, JsonElement right, string path, List<JsonDiffChange> changes)
{
if (DeepEqual(left, right)) return;
if (left.ValueKind == JsonValueKind.Object && right.ValueKind == JsonValueKind.Object)
{
// Sorted union of both key sets (key order never matters).
// StringComparer.Ordinal = UTF-16 code-unit order, like JS sort.
var keys = new SortedSet<string>(StringComparer.Ordinal);
foreach (var p in left.EnumerateObject()) keys.Add(p.Name);
foreach (var p in right.EnumerateObject()) keys.Add(p.Name);
foreach (string key in keys)
{
string child = path + "." + key;
bool hasLeft = left.TryGetProperty(key, out JsonElement lv);
bool hasRight = right.TryGetProperty(key, out JsonElement rv);
if (!hasLeft)
changes.Add(new JsonDiffChange { Path = child, Type = "added", After = RawText(rv) });
else if (!hasRight)
changes.Add(new JsonDiffChange { Path = child, Type = "removed", Before = RawText(lv) });
else
Walk(lv, rv, child, changes);
}
return;
}
if (left.ValueKind == JsonValueKind.Array && right.ValueKind == JsonValueKind.Array)
{
int shared = Math.Min(left.GetArrayLength(), right.GetArrayLength());
for (int i = 0; i < shared; i++)
Walk(left[i], right[i], path + "[" + i + "]", changes);
for (int i = shared; i < right.GetArrayLength(); i++)
changes.Add(new JsonDiffChange { Path = path + "[" + i + "]", Type = "added", After = RawText(right[i]) });
for (int i = shared; i < left.GetArrayLength(); i++)
changes.Add(new JsonDiffChange { Path = path + "[" + i + "]", Type = "removed", Before = RawText(left[i]) });
return;
}
changes.Add(new JsonDiffChange { Path = path, Type = "changed", Before = RawText(left), After = RawText(right) });
}
}
// Example:
// JsonDiffResult r = JsonDiff.Diff("{\"name\": \"ada\"}", "{\"name\": \"grace\"}");
// // r.Same == false, r.Error == null
// // r.Changes[0]: Path "$.name" Type "changed" Before "\"ada\"" After "\"grace\"" (raw JSON text)
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 →