How to Validate JSON Types per Key in Python
Load a JSON object and validate the type of each key against an expected schema, reporting missing or mismatched fields.
Python code
33 linesimport json
from typing import Any, Dict, Type
def validate_json_types(data: Dict[str, Any], schema: Dict[str, Type]) -> Dict[str, str]:
"""Validate that each key in data matches the expected type in schema."""
errors = {}
for key, expected_type in schema.items():
if key not in data:
errors[key] = "missing"
elif not isinstance(data[key], expected_type):
errors[key] = f"expected {expected_type.__name__}, got {type(data[key]).__name__}"
return errors
if __name__ == "__main__":
# Load JSON from a file
json_data = '{"name": "Alice", "age": 30, "active": true}'
data = json.loads(json_data)
# Define expected types per key
schema = {
"name": str,
"age": int,
"active": bool
}
errors = validate_json_types(data, schema)
if errors:
print("Validation errors:")
for key, error in errors.items():
print(f" {key}: {error}")
else:
print("All fields validated successfully.")
Output
All fields validated successfully.
How it works
The function validate_json_types iterates over the schema dictionary. For each key, it first checks if the key exists in the loaded data; if missing, it records an error. Otherwise, it uses isinstance to verify the value matches the expected type. Using type(...).__name__ gives a clear error message for mismatches. This pattern keeps validation centralized and reusable.
Common mistakes
- Forgetting that JSON booleans are case-sensitive: true/false, not True/False.
- Using `isinstance` with a tuple of types when expecting multiple types, which is not handled by a simple dict schema.
- Not handling nested objects or arrays inside the JSON — this validator only checks top-level keys.
- Assuming all keys exist; the function handles missing keys but you must include them in the schema.
Variations
- Use Pydantic models with `model_validate` for automatic type coercion and error messages.
- Use a list of expected types per key, e.g., `{"age": (int, float)}`, and check `isinstance` against the tuple.
Real-world use cases
- Validating the payload of an incoming API request before processing it in a Flask or FastAPI endpoint.
- Checking that configuration loaded from a JSON file matches the expected types before the app starts.
- Ensuring that data pulled from a third-party webhook meets the contract before writing it to a database.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.