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:

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

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

Practice this problem

Related problems