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.

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

Python code

28 lines
Python 3.9+
import 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

stdout
{'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

  1. Use `json.loads(path.read_text(encoding="utf-8"))` to read the entire file as text first
  2. 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

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.