How to Validate JSON Schema Shape in Python
Validate JSON data against a schema using manual checks for required fields, types, and constraints.
Python code
44 linesimport 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
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
- Use `jsonschema` library for complex schemas with nested validation
- 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
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.