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.
Python code
24 linesimport 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
{'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
- Use `Path.read_text()` and `Path.write_text()` with `json.loads` and `json.dumps` for even shorter file I/O.
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.