Parse JSON files in Python with error handling
Quick Answer
Use `json.load(f)` inside a `with open()` context manager to safely load JSON files — always include try/except for malformed JSON.
1import json
2
3# Simple read
4with open('data.json', 'r') as f:
5 data = json.load(f)
6
7print(data)
8
9# With error handling
10try:
11 with open('config.json', 'r') as f:
12 config = json.load(f)
13 print(f"Loaded config: {config}")
14except FileNotFoundError:
15 print("Config file not found")
16except json.JSONDecodeError as e:
17 print(f"Invalid JSON: {e}")
18
19# Accessing nested data
20user_data = {
21 "users": [
22 {"id": 1, "name": "Alice"},
23 {"id": 2, "name": "Bob"}
24 ]
25}
26
27first_user = user_data['users'][0]
28print(first_user['name']) # 'Alice'JSON is everywhere — configuration files, API responses, databases all use JSON. Python's built-in `json` module makes parsing trivial, but you must handle file I/O errors (missing file) and parse errors (invalid JSON) gracefully.
Use `json.dumps(data, indent=2)` to get nicely formatted JSON. Useful for logging and debugging.
Yes, use `import urllib.request` and `json.load(urllib.request.urlopen(url))`. Or use the `requests` library: `requests.get(url).json()`.
This free python code snippet for read json file is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement read json file quickly and correctly.
All snippets in the Snippetly library follow python best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses python.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.