Open the file and load its contents
with open('data.json', 'r') as file: data = json.load(file)
print(data)
### 2. The Best Practice Way (with Error Handling)
In real-world applications, it is highly recommended to specify the `encoding` and handle potential errors (like the file not existing or the JSON being formatted incorrectly).
```python
import json
file_path = 'data.json'
try:
# encoding='utf-8' prevents errors with special characters on Windows
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
print("Successfully loaded JSON!")
except FileNotFoundError:
print(f"Error: The file {file_path} was not found.")
except json.JSONDecodeError:
print(f"Error: The file {file_path} does not contain valid JSON.")
How JSON translates to Python
When json.load() reads the file, it automatically converts JSON data types into Python data types:
| JSON Type | Python Type |
|---|---|
Object {} |
Dictionary dict |
Array [] |
List list |
String "" |
String str |
Number 123 |
Integer int or Float float |
Boolean true/false |
Boolean True/False |
Null null |
None |
Example of accessing the data:
If your data.json file looks like this:
{
"users": [
{"name": "Alice", "age": 28},
{"name": "Bob", "age": 34}
]
}
You can interact with it exactly like a normal Python dictionary and list: ```python
