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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 16 views 0 copies

Python code

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

stdout
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

  1. Use Pydantic models with `model_validate` for automatic type coercion and error messages.
  2. 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

Run this sample

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

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.