How to Read a JSON File into a Dictionary in Python
Load a JSON file into a Python dictionary using the json.load() function with proper file handling and UTF-8 encoding.
Python code
28 linesimport json
from pathlib import Path
def read_json_file(filepath: str) -> dict:
"""Read a JSON file and return its contents as a dictionary."""
path = Path(filepath)
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
return data
if __name__ == "__main__":
# Create a sample JSON file to demonstrate the function
sample_path = Path("sample_data.json")
sample_data = {
"name": "PythonSkillset",
"version": 1.0,
"topics": ["json", "file-io", "dictionaries"],
"active": True
}
sample_path.write_text(json.dumps(sample_data, indent=2), encoding="utf-8")
# Read the JSON file back into a dictionary
result = read_json_file(sample_path)
print(result)
print(f"Type: {type(result).__name__}")
# Clean up the sample file
sample_path.unlink()
Output
{'name': 'PythonSkillset', 'version': 1.0, 'topics': ['json', 'file-io', 'dictionaries'], 'active': True}
Type: dict
How it works
The json.load(f) call reads the file object f and parses its JSON content into native Python objects — JSON objects become dicts, arrays become lists, strings stay strings, and booleans become Python True/False. The pathlib.Path object handles file path operations cross-platform, and opening the file with an explicit encoding="utf-8" ensures correct handling of non-ASCII characters. The with statement guarantees the file is properly closed even if an exception occurs during parsing.
Common mistakes
- Using `json.loads` instead of `json.load` when reading from a file object
- Forgetting to close the file — use a `with` block to auto-close
- Not specifying `encoding="utf-8"` which can cause UnicodeDecodeError on some platforms
Variations
- Use `json.loads(path.read_text(encoding="utf-8"))` to read the entire file as text first
- Use `try/except FileNotFoundError` to handle missing files gracefully
Real-world use cases
- Loading application configuration files (e.g., settings.json) at startup to populate service options.
- Reading cached or exported data from a JSON file produced by another process or pipeline step.
- Parsing test fixtures or sample datasets stored as JSON files in a test suite.
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.