Recursive AI

Export a document comparison to JSON in C#

OneDiff is a free, open-source diff library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Save a document diff as structured JSON, then read it back and check that the changes account for the new document.

Terminal
dotnet add package RecursiveAI.OneDiff.Documents

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneDiff.Documents;
using OneDiff.Documents.Serialization;
 
// old.txt and new.txt are in the zip.
var result = Comparison.Of("old.txt", "new.txt");
File.WriteAllBytes("changes.json",
    ComparisonJson.Write(result));
var restored = ComparisonJson.Read(
    File.ReadAllBytes("changes.json"));
Console.WriteLine(restored.Verification.Passed);

Writes changes.json.

Text
True

Unzip the example, then dotnet run.

Full program

old.txt contains “Pay in 30 days.” and new.txt contains “Pay in 60 days.”, each followed by a newline. The zip includes both original sample texts. The program writes changes.json, reads it and checks it again. Invalid comparison JSON throws ComparisonFormatException, with syntax-error location fields when applicable.

C#
using OneDiff.Documents;
using OneDiff.Documents.Serialization;
 
var comparison = Comparison.Of("old.txt", "new.txt");
File.WriteAllBytes("changes.json", ComparisonJson.Write(comparison));
var restored = ComparisonJson.Read(File.ReadAllBytes("changes.json"));
Console.WriteLine($"Changes: {restored.Changes.Length}");
Console.WriteLine($"Verified here: {restored.Verification.VerifiedHere}");
Console.WriteLine($"Passed: {restored.Verification.Passed}");
Console.WriteLine($"Check failures: {restored.Check().Length}");
Text
Changes: 1
Verified here: True
Passed: True
Check failures: 0

Variations

Read without rerunning verification. This intentionally leaves the result unverified; it does not trust the saved verification claim.

C#
using OneDiff.Documents;
using OneDiff.Documents.Serialization;
 
var comparison = Comparison.Of("old.txt", "new.txt");
var restored = ComparisonJson.Read(
    ComparisonJson.Write(comparison), verify: false);
Console.WriteLine(restored.Verification.VerifiedHere);
Console.WriteLine(restored.Verification.Passed);
Text
False
False

The short answer

Use ComparisonJson.Write(comparison) to obtain UTF-8 bytes, save those bytes, and restore the result with ComparisonJson.Read. This exports a document comparison, not a semantic comparison of two JSON objects. The two input documents can be plain text, as in the example; JSON is the output format for the changes.

The serialized model preserves the documents, anchors (source locations), alignment (matched content), changes, a hidden-difference ledger (a record of differences excluded from the visible redline), and diagnostics (warnings and errors). It also retains differences folded during normalization: for example, quote styles treated as equivalent. Retaining the model instead of reducing it to old and new strings lets a consumer locate changes and inspect those hidden differences. Use the library’s reader rather than treating a saved “passed” field as proof that an imported comparison is complete.

What the JSON contains

For a OneDiff comparison, use its serialization API instead of applying a general-purpose serializer to the public object graph. ComparisonJson.Write writes the library’s versioned comparison format. The compare-model documentation specifies schema version 1, compact UTF-8, fixed key order, omitted empty optional members and escaped non-ASCII characters.

Its output file is meant for programs: compact JSON will not have a separate indented line for each change. The change data remains structured regardless of whitespace. Preserve the schema and version fields when storing or transporting it so a consumer can identify the format.

Optional typed-change members include the resolved old and new values and whether the edit is substantive. OCR readers can add recognition confidence and possible-error flags. Those fields carry meaning that disappears if an exporter keeps only a pair of displayed strings. An anchor also has a source-dependent meaning; plain-text spans are not the same kind of location as page coordinates.

Selected fields from the real changes.json are shown below, indented for reading. The changes array contains the complete sample change entry; other top-level fields are omitted, so this excerpt is not a complete importable comparison.

JSON
{
  "schema": "onediff.comparison",
  "version": 1,
  "changes": [{
    "id": 0,
    "kind": "replace",
    "link": 1,
    "old": {"nodes": [1], "start": 7, "length": 7, "text": "30 days", "anchor": {"kind": "textSpan", "reference": "text", "start": 0, "length": 15}},
    "new": {"nodes": [1], "start": 7, "length": 7, "text": "60 days", "anchor": {"kind": "textSpan", "reference": "text", "start": 0, "length": 15}},
    "edits": [{"oldStart": 7, "oldLength": 1, "newStart": 7, "newLength": 1, "oldText": "3", "newText": "6"}],
    "decision": {"by": "rule", "source": "semantics.value", "score": 1},
    "type": "duration",
    "oldValue": {"canonical": "30 d", "number": "30", "unit": "d"},
    "newValue": {"canonical": "60 d", "number": "60", "unit": "d"}
  }]
}

The old and new anchors locate their paragraphs in the decoded source text (start: 0, length: 15). Within each paragraph, the change starts at offset 7 and covers “30 days” or “60 days”; its edit records the changed digit. Text offsets and lengths use UTF-16 code units.

How do I export a document diff as JSON in C#?

Create the comparison first, then call ComparisonJson.Write. The snippet at the top includes the complete save-and-read path. Its two UTF-8 text inputs differ only in their payment term. The full program prints the restored change count, verification state and the result of a fresh Check() call.

Reading validates structure and, by default, reruns completeness checks (checks that the recorded edits account for the new content and reverse back to the old content). Verification.Passed is true only when verification performed during that read established it. The stored claim is never simply copied. That is important when files move between processes or arrive from a source your application does not control.

The variation disables verification explicitly. Both VerifiedHere and Passed are then false. Calling Check() returns failures but does not mutate an immutable comparison’s verification result. Read again with verification enabled when your next operation requires a passed result. Keep verification state distinct from “the JSON parsed successfully” in a storage or review interface.

How to compare two JSON files for differences?

If your inputs themselves are JSON documents, distinguish textual differences from structural differences. OneDiff’s plain-text reader can compare their text, but this recipe does not provide property-order-insensitive JSON object comparison. It exports a document diff to JSON; it does not define semantic equality for arbitrary JSON data.

For importing an exported OneDiff file, use ComparisonJson.Read, not a second text comparison against the original JSON bytes. The reader has bounds for input bytes, array length and depth through ComparisonJsonLimits, and reports malformed input through ComparisonFormatException. Syntax failures include line, byte position and path information where applicable. Preserve diagnostics too: a damaged source warning is represented with an old-side or new-side source diagnostic code rather than disappearing during serialization.

All onediff recipes