In this short guide, we will learn how to read JSON files using Python, handle common errors, and work with JSON data efficiently. Whether you're working with API responses, configuration files, or data storage, Python's built-in json module makes reading JSON simple and powerful.
JSON (JavaScript Object Notation) is a lightweight data interchange format used everywhere in modern development. Python's json.load() and json.loads() methods let you parse JSON from files and strings seamlessly.
1. Basic JSON File Reading with json.load()
The simplest way to read a JSON file in Python is using the json.load() method with a file object. This deserializes the JSON content directly into Python dictionaries and lists.
import json
# Reading JSON file
with open('data.json', 'r') as file:
data = json.load(file)
# Pretty print the JSON data
print(json.dumps(data, indent=4))
Output Result:
{
"emp_details": [
{
"emp_name": "John Doe",
"email": "[email protected]",
"job_profile": "intern"
},
{
"emp_name": "Tim Rick",
"email": "[email protected]",
"job_profile": "developer"
},
{
"emp_name": "Mick Jagger",
"email": "[email protected]",
"job_profile": "designer"
}
]
}
How it works:
- The with statement ensures the file is properly closed after reading.
- json.load() parses the JSON file and converts it into a Python dictionary or list.
- The json.dumps() method with indent=4 formats the output for readability.
2. Accessing and Manipulating JSON Data
Once you've loaded JSON data, you can access it like any Python dictionary or list. This is useful for extracting specific values or processing data.
import json
# Read JSON file
with open('data.json', 'r') as file:
data = json.load(file)
# Access specific data
employees = data['emp_details']
# Loop through employees
for emp in employees:
print(f"Name: {emp['emp_name']}, Role: {emp['job_profile']}")
# Access first employee's email
first_email = data['emp_details'][0]['email']
print(f"\nFirst employee email: {first_email}")
# Count total employees
print(f"Total employees: {len(employees)}")
Output Result:
Name: Joe, Role: intern
Name: Jim, Role: developer
Name: Tim, Role: designer
First employee email: [email protected]
Total employees: 3
Real-world use: This pattern is essential when working with API responses, configuration files, or database exports where you need to extract and process specific fields.
3. Error Handling: FileNotFoundError and JSONDecodeError
Production-ready code needs proper error handling for JSON operations. The two most common errors are FileNotFoundError (missing file) and JSONDecodeError (malformed JSON).
import json
def safe_read_json(filename):
"""Safely read JSON file with error handling"""
try:
with open(filename, 'r') as file:
data = json.load(file)
return data
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return None
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON format - {e}")
return None
except Exception as e:
print(f"Unexpected error: {e}")
return None
# Try reading existing file
data = safe_read_json('data.json')
if data:
print("Successfully loaded:", list(data.keys()))
# Try reading non-existent file
missing = safe_read_json('missing.json')
# Try reading malformed JSON
bad_data = safe_read_json('bad_format.json')
Output Result:
Successfully loaded: ['emp_details']
Error: File 'missing.json' not found.
Error: Invalid JSON format - Expecting value: line 1 column 1 (char 0)
Why this matters: Error handling prevents your application from crashing when dealing with user-uploaded files, external APIs, or corrupted data. Always use try-except blocks in production code.
4. Reading JSON from String with json.loads()
Sometimes you receive JSON as a string from API responses, web scraping, or network requests. Use json.loads() (note the 's' for string) to parse JSON strings.
import json
# JSON string (common from API responses)
json_string = '''
{
"user_id": 12345,
"username": "john_doe",
"active": true,
"roles": ["admin", "editor"],
"metadata": {
"last_login": "2026-02-14",
"login_count": 42
}
}
'''
# Parse JSON string
user_data = json.loads(json_string)
# Access data
print(f"Username: {user_data['username']}")
print(f"Active: {user_data['active']}")
print(f"Roles: {', '.join(user_data['roles'])}")
print(f"Last login: {user_data['metadata']['last_login']}")
# Check data types
print(f"\nType of parsed data: {type(user_data)}")
print(f"Type of 'active' field: {type(user_data['active'])}")
Output Result:
Username: john_doe
Active: True
Roles: admin, editor
Last login: 2026-02-14
Type of parsed data: <class 'dict'>
Type of 'active' field: <class 'bool'>
Key difference: json.load() reads from file objects, while json.loads() reads from strings. JSON types automatically convert to Python types: JSON objects → dict, JSON arrays → list, JSON booleans → bool, JSON null → None.
Common Use Cases
API Integration: Reading responses from REST APIs
import requests, json
response = requests.get('https://api.example.com/data')
data = json.loads(response.text)
Configuration Files: Loading app settings from JSON
with open('config.json') as f:
config = json.load(f)
db_host = config['database']['host']
Data Processing: Importing datasets for analysis
import pandas as pd
with open('sales_data.json') as f:
sales = json.load(f)
df = pd.DataFrame(sales['transactions'])
Web Scraping: Parsing JSON embedded in HTML pages
Database Exports: Reading MongoDB or NoSQL database dumps
JSON Type Mapping
| JSON Type | Python Type | Example |
|---|---|---|
| object | dict | {"key": "value"} |
| array | list | [1, 2, 3] |
| string | str | "hello" |
| number (int) | int | 42 |
| number (real) | float | 3.14 |
| true/false | bool | True/False |
| null | None | None |
Quick Reference: json Module Methods
| Method | Purpose | Input |
|---|---|---|
json.load(file) |
Read JSON from file | File object |
json.loads(string) |
Read JSON from string | String |
json.dump(obj, file) |
Write JSON to file | Python obj + file |
json.dumps(obj) |
Convert to JSON string | Python object |
Choosing the Right Method
- Reading from file? → Use
json.load(file)(Method 1) - Accessing nested data? → Use dictionary/list indexing (Method 2)
- Production code? → Add error handling with try-except (Method 3)
- API responses/strings? → Use
json.loads(string)(Method 4)
For most JSON file reading tasks, Method 1 combined with Method 3's error handling is your best approach. It's simple, reliable, and production-ready.