Back to all snippets
Library/Python/Read JSON File
pythonbeginnerjsonfilesiodata

How to implement Read JSON File in Python

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.

Code Snippet

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'

What is Read JSON File?

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.

How It Works

  1. 1Open the file with `with open(filename, 'r') as f:`
  2. 2`json.load(f)` parses the file stream and returns a Python dict/list
  3. 3Wrap in try/except to catch `FileNotFoundError` (missing file) and `json.JSONDecodeError` (invalid JSON)
  4. 4Access nested data with dict keys and list indices as normal

Common Use Cases

  • Configuration files - Load app settings from JSON config files
  • Data processing - Parse exported JSON data for analysis
  • API responses - Store and load cached API responses
  • Data pipelines - Read JSON logs and transform them

Key Benefits

  • No external dependencies — `json` is in the standard library
  • Simple one-liner for most cases
  • Works with any JSON structure
  • Integrates seamlessly with Python dicts and lists

Common Mistakes to Avoid

  • Not using a context manager — forgetting `f.close()` leaves file handles open and causes resource leaks
  • Using `eval()` instead of `json.load()` — eval is a security risk and slower
  • Not handling exceptions — unhandled `JSONDecodeError` will crash the program

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more python examples

Frequently Asked Questions

How do I pretty-print JSON in Python?

Use `json.dumps(data, indent=2)` to get nicely formatted JSON. Useful for logging and debugging.

Can I read JSON from a URL?

Yes, use `import urllib.request` and `json.load(urllib.request.urlopen(url))`. Or use the `requests` library: `requests.get(url).json()`.

About This Python Code Snippet

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.

Tags: json, files, io, data  | Language: python  | Difficulty: beginner  | Category: Python

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.