JSON Diff — Find Differences
Difficulty: Hard · Topics: JSON, Recursion, Tree Comparison · Acceptance: 100.0% of 4 submissions
Difficulty: Hard | Tags: JSON, Recursion, Tree Comparison
Description
Given two JSON objects (as strings or maps), find all differences between them. Return a structured diff that identifies:
- Added keys (present in
json2but notjson1) - Removed keys (present in
json1but notjson2) - Modified values (key exists in both but values differ)
Support nested objects and arrays.
Implement:
jsonDiff(json1, json2) → List<Difference>
Where each Difference contains: path, type (ADDED/REMOVED/MODIFIED), oldValue, newValue.
Examples
Example 1:
Input:
json1 = {"name": "Alice", "age": 30}
json2 = {"name": "Alice", "age": 31, "city": "NYC"}
Output:
[
{path: "$.age", type: MODIFIED, old: 30, new: 31},
{path: "$.city", type: ADDED, old: null, new: "NYC"}
]
Example 2 — Nested:
Input:
json1 = {"user": {"name": "Alice", "address": {"city": "LA"}}}
json2 = {"user": {"name": "Bob", "address": {"city": "LA", "zip": "90001"}}}
Output:
[
{path: "$.user.name", type: MODIFIED, old: "Alice", new: "Bob"},
{path: "$.user.address.zip", type: ADDED, old: null, new: "90001"}
]
Example 3 — Array change:
Input:
json1 = {"tags": ["java", "python"]}
json2 = {"tags": ["java", "go"]}
Output:
[
{path: "$.tags[1]", type: MODIFIED, old: "python", new: "go"}
]
Constraints
- JSON nesting depth ≤ 15.
- Array comparison is index-based (not content-aware).
- Both inputs must be valid JSON objects.
- Key order does not matter.
Hints
Hint 1
Use recursion: at each level, compute the union of keys and compare.
Hint 2
Track the current path as you recurse (e.g., "$.user.address").
Follow-up
- Support content-aware array diffing (detect insertions/deletions in arrays, not just index mismatch).