How to Merge Dicts from Two JSON Files Like a Pro
This helper reads two JSON files that contain dicts, merges them with the second file overriding duplicate keys, and saves the result to a new file.
Python code
23 linesimport json
from pathlib import Path
def merge_json_files(file1: str, file2: str, output: str = "merged.json") -> dict:
"""Merge two JSON files containing dicts, with file2 overriding file1."""
data1 = json.loads(Path(file1).read_text())
data2 = json.loads(Path(file2).read_text())
merged = {**data1, **data2}
Path(output).write_text(json.dumps(merged, indent=2))
print(f"Merged {len(data1)} + {len(data2)} keys -> {len(merged)} keys in {output}")
return merged
if __name__ == "__main__":
# Create sample files for demonstration
Path("data_a.json").write_text(json.dumps({"name": "Alice", "age": 30, "city": "NYC"}))
Path("data_b.json").write_text(json.dumps({"age": 31, "country": "USA"}))
result = merge_json_files("data_a.json", "data_b.json")
print(json.dumps(result, indent=2))
Output
Merged 3 + 2 keys -> 4 keys in merged.json
{
"name": "Alice",
"age": 31,
"city": "NYC",
"country": "USA"
}
How it works
The json.loads call converts each file's text into a Python dict. The {**data1, **data2} syntax merges the two dicts, and because data2 comes second, its keys override data1 when they collide (like age). Writing with json.dumps(merged, indent=2) produces a human-readable output file, and the function returns the merged dict for further use.
Common mistakes
- Confusing `json.load` (for file objects) with `json.loads` (for strings); here we read text first and use `json.loads`.
- Assuming both files contain the same type (e.g., lists) — this code only works when each file's top-level structure is a dict.
- Not handling missing files — `Path.read_text()` will raise `FileNotFoundError`.
Variations
- Use `json.load(open(...))` with a context manager if you prefer working directly with file objects.
- Use `dict(data1, **data2)` instead of `{**data1, **data2}` on Python 3.5+.
Real-world use cases
- Merging configuration files where environment-specific overrides come from a second JSON file.
- Combining two user profile payloads from a database backup before syncing to a new service.
- Joining partial API responses that together form a complete resource before caching.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.