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.

Easy Python 3.9+ Aug 9, 2026 Files & data 13 views 0 copies

Python code

21 lines
Python 3.9+
import 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

stdout
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

  1. Use `open()` and `json.load()` to read and parse directly in one step
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.