Merge Two JSON Objects
Difficulty: Medium · Topics: JSON, Recursion, Deep Merge · Acceptance: 100.0% of 1 submissions
Difficulty: Medium | Tags: JSON, Recursion, Deep Merge
Description
Given two JSON objects as strings, merge them into a single JSON object string. If both objects have the same key:
- If both values are objects → recursively merge.
- Otherwise → the second object's value wins.
Implement:
mergeJSON(json1, json2) → String
Examples
Example 1:
Input:
json1 = {"a": 1, "b": 2}
json2 = {"b": 3, "c": 4}
Output: {"a": 1, "b": 3, "c": 4}
Example 2 — Deep merge:
Input:
json1 = {"user": {"name": "Alice", "age": 30}}
json2 = {"user": {"age": 31, "city": "NYC"}}
Output: {"user": {"name": "Alice", "age": 31, "city": "NYC"}}
Example 3:
Input:
json1 = {"a": [1, 2]}
json2 = {"a": [3, 4, 5]}
Output: {"a": [3, 4, 5]}
Explanation: Arrays are replaced, not element-merged.
Constraints
- Both inputs are valid JSON object strings.
- Nesting depth ≤ 10.
- Array values are replaced entirely (no element-level merge).
Hints
Hint 1
Parse both into maps, then write a recursive merge function that checks if both values for a key are maps.