How to Save and Load JSON Files in Python

Create a simple data helper to save Python dictionaries as pretty-printed JSON files and load them back reliably using pathlib and the stdlib json module.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 11 views 0 copies

Python code

24 lines
Python 3.9+
import json
from pathlib import Path
from typing import Any


def save_json(data: Any, filename: str) -> None:
    """Save data as pretty-printed JSON to the current directory."""
    path = Path(filename)
    with path.open("w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)


def load_json(filename: str) -> Any:
    """Load and return data from a JSON file."""
    path = Path(filename)
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


if __name__ == "__main__":
    sample = {"name": "Mira", "skills": ["Python", "JSON"], "level": 3}
    save_json(sample, "sample_data.json")
    loaded = load_json("sample_data.json")
    print(loaded)

Output

stdout
{'name': 'Mira', 'skills': ['Python', 'JSON'], 'level': 3}

How it works

The save_json function uses pathlib.Path to open a file for writing and json.dump with indent=2 and ensure_ascii=False to produce readable JSON that preserves non-ASCII characters. The load_json function opens the file for reading and json.load parses the content back into a Python dictionary. Running the script as the main module creates sample_data.json in the current directory, then reads it back and prints the dictionary with standard Python syntax. This pattern cleanly separates file I/O from business logic, making it reusable across projects.

Common mistakes

  • Calling `json.dumps` instead of `json.dump` when writing directly to a file, then forgetting to close it manually.
  • Hardcoding file paths without `pathlib`, which breaks on different operating systems.
  • Not using `ensure_ascii=False`, so non-English characters get escaped to \u sequences in the output file.

Variations

  1. Use `Path.read_text()` and `Path.write_text()` with `json.loads` and `json.dumps` for even shorter file I/O.
  2. Add a `pretty=True` parameter to toggle indentation, or support append mode for log-style JSON lines.

Real-world use cases

  • Persisting user preferences or app settings to a configuration file that must be human-readable.
  • Caching API responses locally so subsequent runs don't hit the network again.
  • Exporting processed data to a JSON file for sharing with other tools or non-Python systems.

Sponsored

Run this sample

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

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.