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.
Python code
30 linesimport 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
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
- Use `json.loads(Path(filepath).read_text())` for a one-liner file read.
- 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
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.