How to Validate a JSON File in Python
A beginner-friendly Python helper that reads a JSON file, catches common errors, and returns a status dictionary.
Python code
21 linesimport json
from pathlib import Path
def get_valid_json_data(file_path: str) -> dict:
file = Path(file_path)
if not file.exists():
return {"status": "error", "message": f"File not found: {file_path}"}
try:
data = json.loads(file.read_text())
except json.JSONDecodeError as e:
return {"status": "error", "message": f"Invalid JSON: {e}"}
if not isinstance(data, dict):
return {"status": "error", "message": "Root must be a JSON object"}
return {"status": "valid", "data": data}
if __name__ == "__main__":
result = get_valid_json_data("example_data.json")
print(result["status"])
Output
valid
How it works
This function uses pathlib.Path to safely handle file paths and the standard library json module to parse content. It checks for file existence first, then catches json.JSONDecodeError to handle malformed JSON gracefully. It also verifies that the parsed data is a dictionary, since many use cases expect a top-level object. The returned dictionary provides a consistent interface for callers to check status and handle errors or access data.
Common mistakes
- Forgetting to close the file when using open() instead of Path.read_text()
- Not distinguishing between file not found and invalid JSON errors
- Assuming the root JSON element is a dictionary without checking
- Using `json.load` instead of `json.loads` when reading from a file object
Variations
- Use `open()` and `json.load()` to read and parse directly in one step
- Return the parsed dict directly and raise exceptions for caller to handle
Real-world use cases
- Validating configuration files that must have a specific structure before application startup.
- Checking that API response bodies stored as JSON files are well-formed in a data pipeline.
- Ensuring user-uploaded JSON files are safe to process in a web backend.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.