How to Read a JSON File in Python

What you’ll build or solve

You’ll read a JSON file from disk and turn it into Python data like dicts and lists.

When this approach works best

Reading a JSON file works well when you:

  • Load app settings like feature flags, UI preferences, or environment-specific config.
  • Process exported data, like a list of users, products, or events saved as JSON.
  • Build small utilities that read structured input for reporting or automation.

Skip this approach if the file is extremely large, and you only need a tiny slice of it. A streaming parser or a different storage format may fit better.

Prerequisites

  • Python 3 installed
  • You know what JSON looks like, objects and arrays
  • Your file contains valid JSON, double quotes, no trailing commas, no comments

Step-by-step instructions

1) Load JSON from a file

Use the built-in json module.

Option A (most common): json.load() reads from a file object

Option B: json.loads() parses a string

import json
from pathlib import Path

# Option A: Load directly from a file object
with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

# Option B: Load from a string you already have
text = Path("data.json").read_text(encoding="utf-8")
data = json.loads(text)

What to look for: json.load() reads from a file object, json.loads() parses a string.

If you’re dealing with folders and want portable paths across operating systems, see Example 2.


2) Access the data safely

First, confirm what you loaded. JSON at the top level is usually a dict or a list.

if isinstance(data, dict):
    print("Top-level keys:", list(data.keys()))
elif isinstance(data, list):
    print("Top-level list length:", len(data))

Then access values in a way that matches the shape.

If data is a dict:

project = data.get("project", "unknown")
max_retries = data.get("max_retries", 0)

print(project, max_retries)

If you need a nested value but some keys may be missing, chain .get() with a default dict:

metrics = data.get("metrics", {})
signups = metrics.get("signups", 0)

print(signups)

3) Handle JSON errors

Two errors show up most often:

  • FileNotFoundError when the path is wrong
  • json.JSONDecodeError when the file is not valid JSON
import json
from json import JSONDecodeError
from pathlib import Path

path = Path("data.json")

try:
    with path.open("r", encoding="utf-8") as f:
        data = json.load(f)
except FileNotFoundError:
    print(f"File not found: {path.resolve()}")
except JSONDecodeError as e:
    print("Invalid JSON.")
    print(f"Line {e.lineno}, column {e.colno}: {e.msg}")
else:
    print("Loaded JSON successfully.")

What to look for: The line and column in JSONDecodeError usually point to a missing quote, extra comma, or another formatting issue.


Examples you can copy

Example 1: Read a simple config file

config.json:

{
  "debug": false,
  "base_url": "https://example.com",
  "max_retries": 3
}

Python:

import json
from pathlib import Path

config = json.loads(Path("config.json").read_text(encoding="utf-8"))

debug = config.get("debug", False)
base_url = config.get("base_url", "https://example.com")
max_retries = config.get("max_retries", 0)

print(debug)
print(base_url)
print(max_retries)

Example 2: Read JSON from a file in a subfolder

This helps when your script and your JSON file live in different folders.

import json
from pathlib import Path

# Folder structure example:
# project/
#   app.py
#   data/
#     users.json

path = Path(__file__).parent / "data" / "users.json"

with path.open("r", encoding="utf-8") as f:
    users = json.load(f)

print(len(users))

What to look for: Path(__file__).parent anchors the path to the script’s location, not your current terminal folder.


Example 3: Read a list of records and loop through it

users.json:

[
  {"name": "Amina", "role": "admin"},
  {"name": "Luka", "role": "editor"},
  {"name": "Noor", "role": "viewer"}
]

Python:

import json

with open("users.json", "r", encoding="utf-8") as f:
    users = json.load(f)

for user in users:
    print(f'{user["name"]} -> {user["role"]}')

Example 4: Read nested JSON and pull out a few values

report.json:

{
  "run_id": "2026-02-16T10:15:00Z",
  "metrics": {
    "signups": 128,
    "paid_conversions": 14
  },
  "top_sources": ["search", "referral", "email"]
}

Python:

import json
from pathlib import Path

report = json.loads(Path("report.json").read_text(encoding="utf-8"))

run_id = report["run_id"]
signups = report["metrics"]["signups"]
top_source = report["top_sources"][0]

print(run_id)
print(signups)
print(top_source)

Common mistakes and how to fix them

Mistake 1: Reading the file as text and treating it like a dict

What you might do:

with open("data.json", "r", encoding="utf-8") as f:
    data = f.read()

print(data["project"])

Why it breaks: f.read() returns a string, so data["project"] does not make sense.

Correct approach:

import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data["project"])

Mistake 2: Using JSON-like syntax that JSON doesn’t allow

What you might write (invalid JSON):

{ 'project': 'demo', 'max_retries': 3, }

Why it breaks: JSON requires double quotes, and trailing commas are not allowed.

Correct JSON:

{
  "project": "demo",
  "max_retries": 3
}

Then load it:

import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data)

Troubleshooting

If you see FileNotFoundError, print the resolved path and confirm the file exists there:

from pathlib import Path
print(Path("data.json").resolve())

If you see json.JSONDecodeError, go to the line and column shown, then look for a missing quote, an extra comma, or a comment.

If you see UnicodeDecodeError, the file may not be UTF-8. Try a different encoding that matches the source:

from pathlib import Path
text = Path("data.json").read_text(encoding="cp1252")

If you see KeyError, print the keys you actually have, then update your key name or use .get() with a default:

print(list(data.keys()))

If you see TypeError: list indices must be integers, your top-level JSON is a list, not a dict. Loop through it or use an index like data[0].


Quick recap

  • Load the file with json.load() or read text and parse with json.loads().
  • Check if the top-level data is a dict or a list before accessing values.
  • Use .get() and default values when keys might be missing.
  • Catch FileNotFoundError for bad paths and JSONDecodeError for invalid JSON.
  • Use the error’s line and column to locate formatting problems quickly.