Comparateur JSON
Comparez deux objets JSON et visualisez les diffΓ©rences avec suivi dΓ©taillΓ©
What is JSON Diff?
JSON diff is the process of comparing two JSON documents to identify the differences between them. Unlike validation β which checks whether a single document conforms to the JSON grammar β diffing compares two structurally valid documents and produces a changeset describing what was added, removed, or modified. This is essential for tracking configuration changes, debugging API response variations, detecting schema evolution, and auditing data transformations across environments. A reliable JSON diff algorithm must handle the recursive, tree-like nature of JSON β navigating nested objects, arrays with varying orderings, and mixed data types β to produce meaningful, actionable results that developers can use to understand exactly what changed and where.
Diff Algorithms for Structured Data
Comparing two JSON documents is fundamentally different from comparing two flat text files.
Text-based diff tools (like Unix diff) operate on lines and cannot understand
the hierarchical structure of JSON. A property that moves from line 3 to line 7 due to
reformatting would appear as a deletion and addition in text diff, even though the data is
semantically identical. JSON diff algorithms work at the structural level, understanding
that objects are unordered key-value maps and arrays are ordered sequences.
Tree comparison (recursive descent): The most common approach treats both JSON documents as trees and walks them recursively. At each node, the algorithm compares values by type first β if types differ, the entire node is marked as replaced. For objects, it compares keys: keys present only in the left document are deletions, keys only in the right are additions, and shared keys trigger recursive comparison of their values. For arrays, comparison is more complex because element identity is positional unless a key-based matching strategy is applied.
Key-based matching: When comparing arrays of objects, positional comparison
often produces misleading results. If an element is inserted at the beginning of an array,
a naive positional diff reports every subsequent element as modified. Key-based matching
uses a designated field (like id or name) to correlate elements
across the two arrays, producing diffs that reflect actual semantic changes rather than
positional shifts. This technique is critical for comparing collections of records such as
user lists, configuration entries, or API resource arrays.
Longest Common Subsequence (LCS): For arrays without identifiable keys (like arrays of primitives), the LCS algorithm finds the longest sequence of elements that appears in both arrays in the same order. Elements not in the LCS are classified as additions or deletions. This provides optimal minimal diffs for ordered sequences but has O(nΓm) complexity, which can be expensive for very large arrays.
Change Detection Types
A comprehensive JSON diff tool categorizes changes into distinct types that communicate exactly what happened between two document versions. Understanding these categories helps developers interpret diff output and take appropriate corrective action:
- Additions: A key or array element exists in the right document but not
in the left. In patch notation, this is an
addoperation. New configuration properties, added array items, and newly introduced nested objects all fall into this category. - Deletions: A key or element exists in the left document but is absent
from the right. This is a
removeoperation. Deleted fields, removed array entries, and pruned subtrees are deletions. - Modifications (replacements): A key exists in both documents but its
value differs. This can mean a string changed content, a number changed magnitude, a boolean
flipped, or an entire subtree was swapped for a different structure. The
replaceoperation captures this. - Type changes: A special case of modification where the JSON type itself
changed β for example, a value that was a string
"42"became a number42, or an object was replaced by an array. Type changes often indicate breaking schema changes that require code updates in consumers. - Moves: An element relocated within an array or an object key was renamed.
The JSON Patch specification (RFC 6902) includes a
moveoperation for this, though detecting moves algorithmically is more complex than detecting simple add/remove pairs.
Distinguishing between these change types allows developers to filter diffs by severity β for example, treating type changes as breaking changes while allowing value modifications in non-critical fields. Diff tools that report only generic "changed" results without categorization force developers to manually inspect every difference.
Practical Use Cases for JSON Diff
JSON diff serves as a foundational operation in many development workflows where tracking changes to structured data is critical:
API response comparison: When debugging unexpected behavior, comparing the actual API response against an expected baseline reveals exactly which fields changed. This is invaluable during API version migrations, where you can diff responses from v1 and v2 endpoints to understand the full impact of the upgrade on your client code.
Configuration drift detection: Infrastructure-as-code and application configurations stored as JSON (Terraform state, package.json, tsconfig.json) change over time. Diffing the current state against a known-good baseline detects drift β unauthorized changes, accidental modifications, or side effects from automated tools that silently alter configuration files.
Schema evolution tracking: As APIs evolve, their response schemas gain new fields, deprecate old ones, and change value types. Comparing JSON Schema documents or sample responses across versions creates a changelog that documents the evolution path and helps consumers plan their migration strategy.
Test snapshot comparison: Test frameworks that use JSON snapshots (like Jest snapshot testing) rely on JSON diff internally to report which parts of a component's output changed. Understanding how diff works helps developers write more stable snapshots that do not break on irrelevant ordering changes.
Handling Complex Diff Scenarios
Real-world JSON documents present challenges that simple recursive comparison cannot handle well without additional strategies:
Array ordering: JSON arrays are ordered by definition, but many applications use arrays as unordered sets (for example, a list of tags or permissions). A naive diff reports differences when the same elements appear in different orders. Advanced diff tools offer an option to treat arrays as sets, comparing by element content rather than position, which eliminates false positives from harmless reorderings.
Deeply nested objects: Documents with many levels of nesting produce diff
paths like /users/0/address/coordinates/latitude. Representing changes at
leaf nodes with their full path context helps developers locate the change without mentally
navigating the tree. JSON Pointer notation (RFC 6901) provides a standard way to express
these paths unambiguously.
Large documents: Diffing multi-megabyte JSON files (database exports, log aggregations, analytics datasets) requires memory-efficient algorithms. Streaming parsers that process documents incrementally, or Web Workers that offload comparison to background threads, prevent the browser from freezing during heavy comparisons. Chunked output that displays differences progressively improves the user experience for large diffs.
Whitespace and formatting differences: Two documents that are semantically identical but formatted differently (different indentation, key ordering in objects) should produce an empty diff. A proper JSON diff algorithm compares parsed structures, not raw text, ensuring that cosmetic formatting changes never appear as actual differences.
Code Examples
Comparing two JSON documents and generating a diff
// Original JSON document
const original = {
"name": "API Config",
"version": "2.1.0",
"endpoints": [
{ "path": "/users", "method": "GET", "auth": true },
{ "path": "/posts", "method": "GET", "auth": false }
],
"timeout": 30,
"retries": 3
};
// Modified JSON document
const modified = {
"name": "API Config",
"version": "2.2.0",
"endpoints": [
{ "path": "/users", "method": "GET", "auth": true },
{ "path": "/posts", "method": "GET", "auth": true },
{ "path": "/comments", "method": "POST", "auth": true }
],
"timeout": 60,
"retries": 3,
"rateLimit": { "requests": 100, "window": "1m" }
};
// Resulting diff output:
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// β Modified: /version β
// β "2.1.0" β "2.2.0" β
// β β
// β Modified: /endpoints/1/auth β
// β false β true β
// β β
// β Added: /endpoints/2 β
// β { "path": "/comments", "method": "POST", ... } β
// β β
// β Modified: /timeout β
// β 30 β 60 β
// β β
// β Added: /rateLimit β
// β { "requests": 100, "window": "1m" } β
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Summary: 2 additions, 0 deletions, 3 modificationsJSON Patch (RFC 6902) representation of changes
[
{ "op": "replace", "path": "/version", "value": "2.2.0" },
{ "op": "replace", "path": "/endpoints/1/auth", "value": true },
{ "op": "add", "path": "/endpoints/2", "value": {
"path": "/comments", "method": "POST", "auth": true
}},
{ "op": "replace", "path": "/timeout", "value": 60 },
{ "op": "add", "path": "/rateLimit", "value": {
"requests": 100, "window": "1m"
}}
]Standards & Specifications
- RFC 6902 β JSON Patch β defines operations (add, remove, replace, move, copy, test) for expressing changes between JSON documents
- RFC 6901 β JSON Pointer β string syntax for identifying specific values within a JSON document, used in diff paths
- RFC 7396 β JSON Merge Patch β a simpler alternative to JSON Patch that uses a partial document to describe changes
Questions FrΓ©quentes
What is JSON diff?
JSON diff is a comparison tool that identifies all differences between two JSON objects. It shows you exactly what properties were added, removed, or modified, making it easy to track changes in structured data. This is especially useful for debugging, testing, and version control.
How does the tool handle nested objects?
The tool performs deep comparison, meaning it recursively compares all nested objects and arrays at any depth. Each difference is reported with its full path, so you can see exactly where in the structure the change occurred. For example, 'user.address.city' shows a change in the city property nested within address within user.
Can it compare arrays?
Yes! The tool compares arrays element by element. It detects when array elements are added, removed, or modified. Array differences are shown with bracket notation, like '[0]' for the first element or '[2].name' for a property within an array element.
What happens with large JSON files?
For files larger than 100KB combined, the tool automatically uses Web Workers to perform the comparison in a background thread. This prevents the browser from freezing and keeps the interface responsive. You'll see a processing indicator while the comparison is running.
Is my data sent to a server?
No, all JSON comparison happens entirely in your browser. Your data never leaves your device, ensuring complete privacy and security for sensitive information. This also means the tool works offline once the page is loaded.
Can I compare invalid JSON?
No, both JSON inputs must be valid. If either input has syntax errors, the tool will display an error message indicating which side has the problem. You can use our JSON Validator tool to check your JSON syntax before comparing.
How do I interpret the diff results?
The results show three types of changes: Added (+) means the property exists in the right JSON but not the left; Removed (-) means it exists in the left but not the right; Modified (~) means the property exists in both but with different values. Each difference includes the full path and the values from both sides.
Can I compare JSON with different structures?
Yes! The tool handles JSON objects with completely different structures. It will identify all properties that exist in one but not the other, as well as any shared properties that have different values. This makes it useful for comparing data from different API versions or schema migrations.