How to Validate JSON Schema Shape in Python

Validate JSON data against a schema using manual checks for required fields, types, and constraints.

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

Python code

44 lines
Python 3.9+
import json
from typing import Any, Dict

def validate_person_schema(data: Dict[str, Any]) -> bool:
    """Validate a person object against expected schema shape."""
    if not isinstance(data, dict):
        return False
    
    # Required fields check
    required_fields = {"name", "age", "email"}
    if not required_fields.issubset(data.keys()):
        return False
    
    # Type checks
    if not isinstance(data["name"], str):
        return False
    if not isinstance(data["age"], int) or data["age"] < 0:
        return False
    if not isinstance(data["email"], str) or "@" not in data["email"]:
        return False
    
    # Optional fields check
    if "address" in data and not isinstance(data["address"], dict):
        return False
    if "hobbies" in data and not isinstance(data["hobbies"], list):
        return False
    
    return True

if __name__ == "__main__":
    valid_person = {
        "name": "Alice",
        "age": 30,
        "email": "alice@example.com",
        "hobbies": ["reading", "hiking"]
    }
    invalid_person = {
        "name": "Bob",
        "age": -5,
        "email": "bob-at-example.com"
    }
    
    print(f"Valid person: {validate_person_schema(valid_person)}")
    print(f"Invalid person: {validate_person_schema(invalid_person)}")

Output

stdout
Valid person: True
Invalid person: False

How it works

The validate_person_schema function checks JSON data step by step. First, it verifies the input is a dictionary using isinstance. Then it uses a set intersection to confirm all required fields exist. Type checks ensure name is a string, age is a non-negative integer, and email contains an @ symbol. Optional fields like address and hobbies are validated only if present using the in operator. This manual approach gives you full control without external dependencies.

Common mistakes

  • Forgetting to check if the input is a dictionary before accessing keys
  • Using `==` instead of `isinstance()` for type validation
  • Not handling optional fields when they're absent from the data
  • Assuming `age` as a string instead of an integer

Variations

  1. Use `jsonschema` library for complex schemas with nested validation
  2. Create a dataclass with `__post_init__` for validation on instantiation

Real-world use cases

  • Validating webhook payloads from third-party APIs before processing them in your application.
  • Checking user input from a REST endpoint satisfies required fields for database insertion.
  • Verifying configuration files loaded from JSON match expected structure in a data pipeline.

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.