Skip to content
TheChatArchiveThe Chat Archive
GPT 5.1 Codex Max· openaiHugging Face Frontier Reasoning Traces

Write a JSON schema validator from scratch supporting type, properties, required, and…

  1. User

    Write a JSON schema validator from scratch supporting type, properties, required, and nested objects and arrays. Don't use the jsonschema library - implement recursive validation logic manually.

  2. Assistant

    Providing JSON schema validator code

    Here's a minimal Python JSON schema validator supporting type, properties, required, and nested objects/arrays with recursive logic as requested:

    def validate_data(schema, data):
        def check_type(expected_type, value):
            type_map = {
                "object": dict,
                "array": list,
                "string": str,
                "number": (int, float),
                "integer": int,
                "boolean": bool,
            }
            if isinstance(expected_type, list):
                return any(isinstance(value, type_map.get(t, object)) for t in expected_type)
            else:
                return isinstance(value, type_map.get(expected_type, object))
    
        def validate(schema, data):
            # Type check
            if "type" in schema:
                if not check_type(schema["type"], data):
                    return False
    
            # Object validation
            if isinstance(data, dict):
                props = schema.get("properties", {})
                required = schema.get("required", [])
                # Check required fields
                if any(r not in data for r in required):
                    return False
                # Validate properties
                for key, subschema in props.items():
                    if key in data and not validate(subschema, data[key]):
                        return False
    
            # Array validation
            if isinstance(data, list):
                items_schema = schema.get("items")
                if items_schema:
                    for item in data:
                        if not validate(items_schema, item):
                            return False
    
            return True
    
        return validate(schema, data)
    ```</think>
    Below is a simple Python implementation of a JSON schema validator that supports the following keywords:
    
    - `type` (object, array, string, number, integer, boolean)
    - `properties`
    - `required`
    - (Nested) objects and arrays via recursive calls
    - Optional `items` for array validation
    
    It does **not** use any external `jsonschema` library. You can adjust or extend it as needed.
    
    ```python
    def validate_type(expected_type, value):
        """Check if value matches the schema's 'type' keyword."""
        # Map JSON Schema types to Python types
        type_map = {
            "object": dict,
            "array": list,
            "string": str,
            "number": (int, float),
            "integer": int,
            "boolean": bool,
            "null": type(None),
        }
    
        # If schema's "type" is a list, any match is acceptable
        if isinstance(expected_type, list):
            return any(validate_type(t, value) for t in expected_type)
    
        py_type = type_map.get(expected_type)
        return isinstance(value, py_type)
    
    
    def validate(schema, data, path=""):
        """
        Recursively validate `data` against `schema`.
        Returns (True, None) if valid; otherwise (False, error_message).
        """
        # Ensure "type" is enforced if present
        if "type" in schema:
            if not validate_type(schema["type"], data):
                return False, f"{path or 'data'}: Expected type {schema['type']} but got {type(data).__name__}"
    
        # If type is "object", handle properties and required
        if schema.get("type") == "object":
            # Check required properties
            required = schema.get("required", [])
            for req_prop in required:
                if not isinstance(req_prop, str) or req_prop not in data:
                    return False, f"{path or 'data'}: Missing required property '{req_prop}'"
    
            # Validate properties if defined
            properties = schema.get("properties", {})
            for prop_name, prop_schema in properties.items():
                if prop_name in data:
                    new_path = f"{path}.{prop_name}" if path else prop_name
                    ok, err = validate(prop_schema, data[prop_name], new_path)
                    if not ok:
                        return False, err
    
        # If type is "array", validate each element with "items" (if provided)
        if schema.get("type") == "array":
            items_schema = schema.get("items")
            if items_schema:
                for idx, item in enumerate(data):
                    new_path = f"{path}[{idx}]" if path else f"[{idx}]"
                    ok, err = validate(items_schema, item, new_path)
                    if not ok:
                        return False, err
    
        return True, None
    
    
    # Example usage:
    if __name__ == "__main__":
        # Sample schema
        schema_example = {
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "age":  {"type": "integer"},
                "tags": {
                    "type": "array",
                    "items": {"type": "string"}
                },
                "address": {
                    "type": "object",
                    "required": ["city"],
                    "properties": {
                        "city": {"type": "string"},
                        "zip":  {"type": "integer"}
                    }
                }
            },
            "required": ["name", "age"]
        }
    
        # Valid data
        data_valid = {
            "name": "Alice",
            "age": 30,
            "tags": ["student", "developer"],
            "address": {
                "city": "Wonderland",
                "zip": 12345
            }
        }
    
        # Invalid data (missing required "age")
        data_invalid = {
            "name": "Bob",
            "tags": ["tester"]
        }
    
        ok, error = validate(schema_example, data_valid)
        print("Valid data result:", ok, error)
    
        ok, error = validate(schema_example, data_invalid)
        print("Invalid data result:", ok, error)
    
    • How it works:
      1. validate() checks the type of the current piece of data against the schema’s type.
      2. If it’s an object, it verifies required keys and then recurses into each property defined by properties.
      3. If it’s an array, it verifies each element against the items schema (if provided).
      4. On success, it returns (True, None); on failure, (False, "error message").

    You can expand this validator with additional JSON Schema features as needed.