How to Load and Save JSON Files in Python

Load and save JSON files with pretty formatting using Python's standard library json module and pathlib.

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

Python code

30 lines
Python 3.9+
import json
from pathlib import Path


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


def save_json(filepath: str, data: dict) -> None:
    """Save data to a JSON file with pretty formatting."""
    path = Path(filepath)
    with path.open("w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)


if __name__ == "__main__":
    sample_data = {
        "users": [
            {"name": "Alice", "age": 30},
            {"name": "Bob", "age": 25},
        ],
        "count": 2,
    }

    save_json("sample_data.json", sample_data)
    loaded_data = load_json("sample_data.json")
    print(f"Saved and loaded {len(loaded_data['users'])} users successfully.")

Output

stdout
Saved and loaded 2 users successfully.

How it works

The load_json function uses json.load to parse JSON content directly from a file object, while save_json uses json.dump to write Python dictionaries as JSON. The pathlib.Path object provides a clean, cross-platform way to open files. The ensure_ascii=False parameter preserves non-ASCII characters (like emoji or accented text) in the saved file. The indent=2 parameter produces human-readable, formatted output. This helper pattern is ideal for small CRUD-style applications that need persistent storage.

Common mistakes

  • Forgetting to close the file — always use a `with` block or `contextlib.closing`.
  • Using `json.loads` instead of `json.load` when reading from a file object.
  • Skipping the `encoding="utf-8"` parameter, which can cause Unicode errors on Windows.
  • Assuming the file exists — consider wrapping `load_json` in a `try/except` for `FileNotFoundError`.

Variations

  1. Use `json.loads(Path(filepath).read_text())` for a one-liner file read.
  2. Add a `default` parameter to `json.dump` to handle non-serializable objects (e.g., datetime).

Real-world use cases

  • Persisting user settings or configuration files for a desktop application.
  • Saving and restoring game state or application progress between sessions.
  • Writing response payloads to disk during API integration testing for later inspection.

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.