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.

Easy Python 3.9+ Aug 9, 2026 Files & data 13 views 0 copies

Python code

23 lines
Python 3.9+
import 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

stdout
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

  1. Use `json.load(open(...))` with a context manager if you prefer working directly with file objects.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.