Loading JSON From a File in Python
When working with APIs, configuration files, or structured datasets, JSON is one of the most widely used formats. Python provides a built-in json module that makes it simple and efficient to load JSON data from files into dictionaries or lists.
Why Load JSON From a File?
- Configuration Management:Many apps store settings in config.json
- Data Processing: JSON is common in logs, datasets, and API exports
- Portability: Easy to share structured data between systems
- Reliability: JSON ensures consistent formatting across environments
Method 1: Using json.load()
The json.load() function reads JSON data directly from a file object and converts it to a Python dictionary or list.
Example
import json
Open JSON file
with open("data.json", "r") as file:
data = json.load(file)
Use the loaded data
print(data)
How It Works
- open("data.json") opens the file in read mode.
- json.load() parses the JSON content.
- The result is converted into native Python types such as:
dict
list
int, float
str
bool, None
Method 2: Handling Errors While Loading JSON
JSON files may sometimes be corrupted or contain syntax errors. You should handle exceptions to avoid crashes.
Example with Error Handling
import json
try:
with open("data.json", "r") as file:
data = json.load(file)
print("JSON loaded successfully!")
except FileNotFoundError:
print("Error: File not found.")
except json.JSONDecodeError as e:
print("Invalid JSON:", e)
This makes your code safer and more reliable in production environments.
Method 3: Loading JSON with UTF-8 Encoding
If your file contains Unicode or non-ASCII characters (e.g., emojis, multilingual content), specify encoding:
import json
with open("data.json", "r", encoding="utf-8") as file:
data = json.load(file)
Method 4: Loading Large JSON Files Safely
For extremely large files, loading all data at once may use too much memory. Instead, you can load data incrementally using streaming libraries like ijson (third-party), but with built-in tools:
Line-by-line JSON objects example:
import json
data_list = []
with open("large.json", "r") as file:
for line in file:
data_list.append(json.loads(line))
Best Practices
- Always use with open() to ensure the file closes automatically.
- Validate the JSON file format if the source is external.
- Add error handling in production applications.
- Use UTF-8 encoding when working with multilingual or emoji-rich data.
- For large datasets, consider streaming instead of loading everything at once.
Give try to online and free jsonformatter
Top comments (0)