How to Read JSON File in Python: Simple Guide
To read a JSON file in Python, use the
json module. Open the file with open(), then load its content using json.load() to get a Python dictionary or list.Syntax
Use the open() function to open the JSON file in read mode. Then use json.load() to convert the JSON content into a Python object like a dictionary or list.
open('filename.json', 'r'): Opens the file for reading.json.load(file_object): Reads and parses JSON data from the file.
python
import json with open('data.json', 'r') as file: data = json.load(file)
Example
This example shows how to read a JSON file named data.json and print its content as a Python dictionary.
python
import json # Assume data.json contains: {"name": "Alice", "age": 30, "city": "New York"} with open('data.json', 'r') as file: data = json.load(file) print(data) print(f"Name: {data['name']}")
Output
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Name: Alice
Common Pitfalls
Common mistakes when reading JSON files include:
- Forgetting to open the file in read mode (
'r'). - Using
json.loads()instead ofjson.load()when reading from a file (the former is for strings). - Not handling exceptions if the file is missing or contains invalid JSON.
python
import json # Wrong: using json.loads() with a file object with open('data.json', 'r') as file: # This will raise an error # data = json.loads(file.read()) pass # Right way: with open('data.json', 'r') as file: data = json.load(file)
Quick Reference
| Step | Code | Description |
|---|---|---|
| 1 | import json | Import the JSON module |
| 2 | with open('file.json', 'r') as f: | Open JSON file in read mode |
| 3 | data = json.load(f) | Load JSON content into Python object |
| 4 | print(data) | Use the data as a Python dictionary or list |
Key Takeaways
Use json.load() to read JSON data directly from a file object.
Always open the JSON file in read mode ('r') before loading.
json.loads() is for JSON strings, not files.
Handle exceptions for missing files or invalid JSON to avoid crashes.
The loaded JSON becomes a Python dictionary or list for easy use.