Recursive JSON Payload Schema Validator

Easy · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Backend gateways and webhook processors routinely verify decoded JSON payloads against declarative contracts before running business logic, collecting every structural error in a single pass so callers can fix malformed payloads without repeated round trips.

Implement JSONSchemaValidator with a validate(schema, data) method that checks an arbitrary JSON-like Python value against a schema dictionary and returns (True, []) when every rule passes, or (False, errors) listing human-readable violation messages in deterministic order.

Class Signature

from typing import Any, Dict, List, Tuple


class JSONSchemaValidator:
    def validate(self, schema: Dict[str, Any], data: Any) -> Tuple[bool, List[str]]:
        """Returns (True, []) when valid, or (False, [error_messages]) when invalid."""
        ...

Schema Keywords & Validation Rules

  1. "type": Expected JSON type—one of "string", "number" (int or float, never bool), "boolean", "object" (dict), or "array" (list). None does not match any of these five types.
    • If "type" is specified and data has any other type, append "<path> must be of type <type>" and skip all remaining keyword checks on that value.
    • If "type" is omitted from a schema, type-specific keywords still apply whenever the runtime value has the matching type (and are ignored for other types).
  2. Numeric bounds (applied to "number" values):
    • "minimum": inclusive lower bound; if value < minimum, append "<path> must be >= <minimum>".
    • "maximum": inclusive upper bound; if value > maximum, append "<path> must be <= <maximum>".
  3. Regular expression (applied to "string" values):
    • "pattern": regex tested with unanchored search (re.search, so start/end anchors apply only when ^ or $ appear in the pattern). On mismatch, append "<path> must match pattern <pattern>".
  4. Object rules (applied to "object" values, evaluated in this order):
    • "required": list of property names that must exist as keys in data (key in data; a key whose value is None counts as present). Checked in schema list order; each absent key appends "missing required property: <child_path>".
    • "properties": dict mapping property names to sub-schemas. Checked in schema dict order for each declared property present in data.
    • "additionalProperties": boolean (defaults to True). When False, checked in data dict order: each key in data not declared in "properties" appends "unexpected property: <child_path>".
  5. Array rules (applied to "array" values):
    • "items": sub-schema validated against every list element in index order 0, 1, ....

Path Formatting

  • The root value itself is named "root".
  • Top-level object fields use their bare key ("price"), while nested object fields join with dots ("shipping.postal_code").
  • Array elements append [<index>] to the array's path ("lines[1]", "matrix[0][2]", or "root[0]" when the root value is an array).

Examples

Example 1

schema = {
    "type": "object",
    "required": ["sku", "price"],
    "additionalProperties": False,
    "properties": {
        "sku": {"type": "string", "pattern": r"^[A-Z]{2}-[0-9]{4}$"},
        "price": {"type": "number", "minimum": 0.5, "maximum": 9999},
        "in_stock": {"type": "boolean"},
    },
}

validator = JSONSchemaValidator()
is_valid, errors = validator.validate(
    schema,
    {"sku": "BK-1042", "price": 24.95, "in_stock": True},
)
# -> (True, [])

Walk-through: Both required keys ("sku" and "price") exist, no undeclared keys appear, "BK-1042" matches ^[A-Z]{2}-[0-9]{4}$, 24.95 lies inside [0.5, 9999], and True is a "boolean".

Example 2

is_valid, errors = validator.validate(
    schema,
    {"sku": "BK-1042", "price": -5, "coupon": "SAVE10"},
)
# -> (False, ["price must be >= 0.5", "unexpected property: coupon"])

Walk-through: "in_stock" is optional so omitting it is fine. "price" fails minimum: 0.5 during property validation, and afterward "coupon" is flagged because additionalProperties is False.

Example 3

order_schema = {
    "type": "object",
    "required": ["lines"],
    "properties": {
        "lines": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["qty"],
                "properties": {"qty": {"type": "number", "minimum": 1}},
            },
        }
    },
}

is_valid, errors = validator.validate(
    order_schema,
    {"lines": [{"qty": 2}, {"qty": "two"}, {}]},
)
# -> (False, ["lines[1].qty must be of type number", "missing required property: lines[2].qty"])

Walk-through: Element 0 passes; element 1's "qty" is a string so it records "lines[1].qty must be of type number" and skips the minimum: 1 check; element 2 omits "qty" so it records "missing required property: lines[2].qty".

Constraints

  • schema is a syntactically valid dictionary whose regex "pattern" strings compile cleanly under Python's re module.
  • Container nesting depth is at most 20 levels.
  • data may contain None, bool, int, float, str, list, and dict values.
  • Remember that isinstance(True, int) is True in Python—boolean values must never be accepted as "number", and integers 0 / 1 must never be accepted as "boolean".

Step-by-step walkthrough

  1. Restate the problem and pin down the contract

    We need to implement JSONSchemaValidator.validate(schema, data), which walks a JSON-like Python value alongside a schema dictionary and returns (True, []) when every rule passes, or (False, errors) containing human-readable error strings for every violation found.

    Because sub-schemas appear inside properties (for objects) and items (for arrays), schemas form a tree mirroring the nested data:

    schema (root: object)
      |-- required: ["sku", "price"]
      |-- additionalProperties: False
      +-- properties:
            |-- "sku"      -> sub-schema (string, pattern: ^[A-Z]{2}-[0-9]{4}$)
            |-- "price"    -> sub-schema (number, minimum: 0.5, maximum: 9999)
            +-- "in_stock" -> sub-schema (boolean)
    

    Before writing code, lock down the exact edge-case rules established by the examples and starter.py:

    • Path formatting: Top-level object fields use their bare name ("price"), nested object fields join with dots ("shipping.postal_code"), array items append [index] ("lines[1]"), and the top-level value itself is called "root" (so items of a root array are "root[0]").
    • Short-circuit on wrong type: If "price" receives "free" (a string instead of a number), report "price must be of type number" and stop checking numeric bounds on "free". Trying "free" < 0.5 in Python would raise a TypeError!
    • Regex pattern matching: Standard JSON Schema treats pattern as a substring search unless anchored with ^ and $ (notice Example 1 explicitly writes r"^[A-Z]{2}-[0-9]{4}$"). Using re.search supports both anchored full matches and unanchored partial matches.
    • Deterministic error order inside an object: Check required first (in schema list order), then present properties (in schema dict order), then unexpected extra properties when additionalProperties is False (in data dict order).
  2. Map Python values to JSON types (and dodge the bool trap)

    Python has one famous type-hierarchy gotcha that trips up many candidates: bool is a subclass of int.

    isinstance(True, int)    -->  True!
    isinstance(False, int)   -->  True!
    True >= 0                -->  True!
    

    If you check isinstance(value, (int, float)) first, {"price": True} will be classified as a "number" and pass minimum: 0.5! Checking isinstance(value, bool) first cleanly separates booleans from numbers.

    Writing one small helper _json_type(value) turns every type check in the validator into a simple string equality check:

    def _json_type(value: Any) -> Optional[str]:
        """Return the JSON Schema type name of a Python value, or None if unsupported (e.g. None)."""
        # CRITICAL: check `bool` BEFORE `(int, float)` because `bool` subclasses `int` in Python
        # (`isinstance(True, int)` is True, and `True >= 0` evaluates to True!).
        if isinstance(value, bool):
            return "boolean"
        if isinstance(value, (int, float)):
            return "number"
        if isinstance(value, str):
            return "string"
        if isinstance(value, dict):
            return "object"
        if isinstance(value, list):
            return "array"
        return None
    

    Notice what happens to None: _json_type(None) returns None, which does not equal any of the five supported schema type strings, so any typed schema cleanly rejects None.

  3. Format field paths and dispatch by type

    As we walk down nested objects and lists, we pass the current path string ("" at the very top) and one shared errors list so every helper can append messages in place without copying lists back up the call stack.

    Three tiny helpers keep path formatting bug-free everywhere, including 2D arrays like matrix[0][1] or root arrays like root[0]:

    def _label(path: str) -> str:
        """Format a path for error messages: the empty root path becomes 'root'."""
        if path:
            return path
        return "root"
    
    
    def _child_path(path: str, name: str) -> str:
        """Extend `path` with an object property name: '' -> 'age', 'user' -> 'user.age'."""
        if path:
            return path + "." + name
        return name
    
    
    def _item_path(path: str, index: int) -> str:
        """Extend `path` with an array index: '' -> 'root[0]', 'tags' -> 'tags[0]'."""
        return f"{_label(path)}[{index}]"
    

    Inside JSONSchemaValidator, instead of a sprawling if/elif chain, we store a dispatch table (a dictionary mapping each type name like "number" or "object" to the method that checks its keywords). Adding a new type or keyword later touches only one small method:

    class JSONSchemaValidator:
        def __init__(self) -> None:
            # _checkers: dispatch table mapping JSON type name -> type-specific validation method.
            # ("boolean" has no extra keywords in this spec, so it needs no entry here.)
            self._checkers: Dict[str, Callable[[Dict[str, Any], Any, str, List[str]], None]] = {
                "number": self._check_number,
                "string": self._check_string,
                "object": self._check_object,
                "array": self._check_array,
            }
            # _regex_cache: maps raw pattern str -> compiled re.Pattern so repeated checks skip compilation.
            self._regex_cache: Dict[str, Any] = {}
    
        def validate(self, schema: Dict[str, Any], data: Any) -> Tuple[bool, List[str]]:
            # Accumulate every violation into one shared list during the recursive walk.
            errors: List[str] = []
            self._validate_node(schema, data, "", errors)
            return len(errors) == 0, errors
    
        def _validate_node(self, schema: Dict[str, Any], value: Any, path: str, errors: List[str]) -> None:
            actual_type = _json_type(value)
            expected_type = schema.get("type")
    
            # Phase 1: check `type` first and short-circuit on mismatch so we never run incompatible
            # checks like comparing a string `"15" < 18` (which would raise TypeError).
            if expected_type is not None and actual_type != expected_type:
                errors.append(f"{_label(path)} must be of type {expected_type}")
                return
    
            # Phase 2: dispatch by `actual_type` so even schemas that omit `"type"` (e.g. `{"minimum": 5}`)
            # still apply numeric keywords to numbers while ignoring non-numbers.
            checker = self._checkers.get(actual_type) if actual_type is not None else None
            if checker is not None:
                checker(schema, value, path, errors)
    

    Look closely at Phase 2: looking up self._checkers.get(actual_type) rather than expected_type means an untyped schema like {"minimum": 5} automatically checks numbers (3 fails) while leaving strings ("abc" passes) alone—matching real JSON Schema semantics!

  4. Validate leaf rules: numbers and regex patterns

    Once _validate_node reaches _check_number, value is guaranteed to be a genuine int or float (never bool or str). Both minimum and maximum are inclusive bounds (>= and <=), so an error fires only on strict < or >:

    • With minimum: 0.5, 0.5 is valid and -5 triggers "<path> must be >= 0.5".
    • Checking minimum and maximum with two separate if statements (rather than elif) ensures independent rules are always checked cleanly.

    For _check_string, we compile each regex string once and cache the compiled pattern in self._regex_cache, then check compiled_regex.search(value) is None:

        def _check_number(self, schema: Dict[str, Any], value: Any, path: str, errors: List[str]) -> None:
            # Both `minimum` and `maximum` are inclusive (>= and <=), so only strict < or > fails.
            if "minimum" in schema and value < schema["minimum"]:
                errors.append(f"{_label(path)} must be >= {schema['minimum']}")
            if "maximum" in schema and value > schema["maximum"]:
                errors.append(f"{_label(path)} must be <= {schema['maximum']}")
    
        def _check_string(self, schema: Dict[str, Any], value: str, path: str, errors: List[str]) -> None:
            pattern = schema.get("pattern")
            if pattern is not None:
                # Standard JSON Schema `pattern` uses unanchored search unless ^ / $ are written.
                compiled_regex = self._compiled(pattern)
                if compiled_regex.search(value) is None:
                    errors.append(f"{_label(path)} must match pattern {pattern}")
    
        def _compiled(self, pattern: str) -> Any:
            if pattern not in self._regex_cache:
                self._regex_cache[pattern] = re.compile(pattern)
            return self._regex_cache[pattern]
    
  5. Validate containers recursively: objects and arrays

    Objects have three distinct responsibilities, executed in order:

    1. required fields: Every field name in schema.get("required", []) must exist as a key in value. Always test if name not in value:—never if value.get(name) is None:—because {"a": None} has key "a" present (with value None), so it should get a type error if "a" expects a string, not a "missing required property" error!
    2. properties sub-schemas: For each (name, sub_schema) in properties, if name in value, recurse into _validate_node(sub_schema, value[name], _child_path(path, name), errors). Optional properties absent from value are simply skipped.
    3. additionalProperties: Defaults to True. When explicitly False, any key in value that is not in properties appends "unexpected property: <child_path>".

    Arrays simply validate each element item at index against schema["items"] (if "items" is specified):

        def _check_object(self, schema: Dict[str, Any], value: Dict[str, Any], path: str, errors: List[str]) -> None:
            properties = schema.get("properties", {})
    
            # Step 1: check required keys in schema order. Use `name not in value` (not `.get()`)
            # so a key explicitly set to `None` counts as present and gets type-checked in Step 2.
            for name in schema.get("required", []):
                if name not in value:
                    errors.append(f"missing required property: {_child_path(path, name)}")
    
            # Step 2: recursively validate every declared property that is actually present in `value`.
            for name, sub_schema in properties.items():
                if name in value:
                    child_path = _child_path(path, name)
                    self._validate_node(sub_schema, value[name], child_path, errors)
    
            # Step 3: if `additionalProperties` is explicitly False (default is True), reject extra keys.
            if schema.get("additionalProperties", True) is False:
                for name in value:
                    if name not in properties:
                        errors.append(f"unexpected property: {_child_path(path, name)}")
    
        def _check_array(self, schema: Dict[str, Any], value: List[Any], path: str, errors: List[str]) -> None:
            item_schema = schema.get("items")
            if item_schema is None:
                return
            # Validate every element in index order, building paths like `tags[0]` or `root[0]`.
            for index, item in enumerate(value):
                item_path = _item_path(path, index)
                self._validate_node(item_schema, item, item_path, errors)
    

    Because the problem guarantees nesting depth <= 20, recursion uses at most ~20 stack frames—nowhere near Python's 1,000-frame recursion limit.

  6. Trace Example 2 and Example 3 step by step

    First, trace Example 2: data = {"sku": "BK-1042", "price": -5, "coupon": "SAVE10"} against the product schema:

    Call / Check                     Path       Value      Outcome
    ------------------------------   --------   --------   ---------------------------------------
    _validate_node (root)            ""         dict       actual "object" == "object" -> ok
      Step 1: required               "sku"      present    ok
                                     "price"    present    ok
      Step 2: properties["sku"]      "sku"      "BK-1042"  type "string" ok; matches ^[A-Z]{2}-[0-9]{4}$
              properties["price"]    "price"    -5         type "number" ok; -5 < 0.5 ->
                                                           append "price must be >= 0.5"
              properties["in_stock"] "in_stock" absent     optional -> skipped
      Step 3: additionalProperties   "coupon"   "SAVE10"   "coupon" not in properties ->
                                                           append "unexpected property: coupon"
    
    Return: (False, ["price must be >= 0.5", "unexpected property: coupon"])
    

    Second, trace how nested paths compose in Example 3 on {"lines": [{"qty": 2}, {"qty": "two"}, {}]}:

    "" -> "lines" -> "lines[0]" -> "lines[0].qty" (2: valid number >= 1)
                  -> "lines[1]" -> "lines[1].qty" ("two": wrong type -> short-circuit!)
                  -> "lines[2]" -> missing required property: lines[2].qty!
    
  7. Put together the complete solution

    Here is the full solution.py with type guards, path helpers, dispatch table, regex cache, and recursive validators:

    from typing import Any, Callable, Dict, List, Optional, Tuple
    import re
    
    
    def _json_type(value: Any) -> Optional[str]:
        """Return the JSON Schema type name of a Python value, or None if unsupported (e.g. None)."""
        # CRITICAL: check `bool` BEFORE `(int, float)` because `bool` subclasses `int` in Python
        # (`isinstance(True, int)` is True, and `True >= 0` evaluates to True!).
        if isinstance(value, bool):
            return "boolean"
        if isinstance(value, (int, float)):
            return "number"
        if isinstance(value, str):
            return "string"
        if isinstance(value, dict):
            return "object"
        if isinstance(value, list):
            return "array"
        return None
    
    
    def _label(path: str) -> str:
        """Format a path for error messages: the empty root path becomes 'root'."""
        if path:
            return path
        return "root"
    
    
    def _child_path(path: str, name: str) -> str:
        """Extend `path` with an object property name: '' -> 'age', 'user' -> 'user.age'."""
        if path:
            return path + "." + name
        return name
    
    
    def _item_path(path: str, index: int) -> str:
        """Extend `path` with an array index: '' -> 'root[0]', 'tags' -> 'tags[0]'."""
        return f"{_label(path)}[{index}]"
    
    
    class JSONSchemaValidator:
        def __init__(self) -> None:
            # _checkers: dispatch table mapping JSON type name -> type-specific validation method.
            # ("boolean" has no extra keywords in this spec, so it needs no entry here.)
            self._checkers: Dict[str, Callable[[Dict[str, Any], Any, str, List[str]], None]] = {
                "number": self._check_number,
                "string": self._check_string,
                "object": self._check_object,
                "array": self._check_array,
            }
            # _regex_cache: maps raw pattern str -> compiled re.Pattern so repeated checks skip compilation.
            self._regex_cache: Dict[str, Any] = {}
    
        def validate(self, schema: Dict[str, Any], data: Any) -> Tuple[bool, List[str]]:
            """Return (True, []) if data is valid, else (False, [error messages])."""
            # Accumulate every violation into one shared list during the recursive walk.
            errors: List[str] = []
            self._validate_node(schema, data, "", errors)
            return len(errors) == 0, errors
    
        def _validate_node(self, schema: Dict[str, Any], value: Any, path: str, errors: List[str]) -> None:
            actual_type = _json_type(value)
            expected_type = schema.get("type")
    
            # Phase 1: check `type` first and short-circuit on mismatch so we never run incompatible
            # checks like comparing a string `"15" < 18` (which would raise TypeError).
            if expected_type is not None and actual_type != expected_type:
                errors.append(f"{_label(path)} must be of type {expected_type}")
                return
    
            # Phase 2: dispatch by `actual_type` so even schemas that omit `"type"` (e.g. `{"minimum": 5}`)
            # still apply numeric keywords to numbers while ignoring non-numbers.
            checker = self._checkers.get(actual_type) if actual_type is not None else None
            if checker is not None:
                checker(schema, value, path, errors)
    
        def _check_number(self, schema: Dict[str, Any], value: Any, path: str, errors: List[str]) -> None:
            # Both `minimum` and `maximum` are inclusive (>= and <=), so only strict < or > fails.
            if "minimum" in schema and value < schema["minimum"]:
                errors.append(f"{_label(path)} must be >= {schema['minimum']}")
            if "maximum" in schema and value > schema["maximum"]:
                errors.append(f"{_label(path)} must be <= {schema['maximum']}")
    
        def _check_string(self, schema: Dict[str, Any], value: str, path: str, errors: List[str]) -> None:
            pattern = schema.get("pattern")
            if pattern is not None:
                # Standard JSON Schema `pattern` uses unanchored search unless ^ / $ are written.
                compiled_regex = self._compiled(pattern)
                if compiled_regex.search(value) is None:
                    errors.append(f"{_label(path)} must match pattern {pattern}")
    
        def _check_object(self, schema: Dict[str, Any], value: Dict[str, Any], path: str, errors: List[str]) -> None:
            properties = schema.get("properties", {})
    
            # Step 1: check required keys in schema order. Use `name not in value` (not `.get()`)
            # so a key explicitly set to `None` counts as present and gets type-checked in Step 2.
            for name in schema.get("required", []):
                if name not in value:
                    errors.append(f"missing required property: {_child_path(path, name)}")
    
            # Step 2: recursively validate every declared property that is actually present in `value`.
            for name, sub_schema in properties.items():
                if name in value:
                    child_path = _child_path(path, name)
                    self._validate_node(sub_schema, value[name], child_path, errors)
    
            # Step 3: if `additionalProperties` is explicitly False (default is True), reject extra keys.
            if schema.get("additionalProperties", True) is False:
                for name in value:
                    if name not in properties:
                        errors.append(f"unexpected property: {_child_path(path, name)}")
    
        def _check_array(self, schema: Dict[str, Any], value: List[Any], path: str, errors: List[str]) -> None:
            item_schema = schema.get("items")
            if item_schema is None:
                return
            # Validate every element in index order, building paths like `tags[0]` or `root[0]`.
            for index, item in enumerate(value):
                item_path = _item_path(path, index)
                self._validate_node(item_schema, item, item_path, errors)
    
        def _compiled(self, pattern: str) -> Any:
            if pattern not in self._regex_cache:
                self._regex_cache[pattern] = re.compile(pattern)
            return self._regex_cache[pattern]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a JSON Schema validator like a building inspector walking through a house with a nested room-by-room checklist:

  • At every stop, the inspector carries three things: the checklist for this part (schema), the actual item being inspected (value), and a breadcrumb label (path, such as "lines[1].qty") so any note on the clipboard (errors) pinpoints the exact location.
  • First, the inspector checks whether value is even the right kind of thing (type: "object", "array", "string", "number", or "boolean"). If a field expects a "number" and receives "two", the inspector logs that single type mismatch and moves on (short-circuiting: stopping downstream checks on a value whose base type is already wrong).
  • If the type matches, a dispatch table (a dictionary mapping each type name like "object" or "number" to its dedicated checker method) runs that type's rules—stepping recursively into child object properties and array items.

A naive validator usually fails in three places. First, writing isinstance(x, (int, float)) in Python silently accepts True and False as numbers because bool subclasses int (isinstance(True, int) is True!). Second, forgetting to return early after a type mismatch causes Python to evaluate comparisons like "two" < 1, crashing with TypeError. Third, returning False on the very first bad field forces API callers to play whack-a-mole across multiple HTTP round trips instead of receiving every payload error at once.

Walk through Example 2—data = {"sku": "BK-1042", "price": -5, "coupon": "SAVE10"}—step by step:

  1. At path = "" (root), data is a dict ("object"), matching type: "object".
  2. _check_object checks required: ["sku", "price"]—both keys exist in data (optional "in_stock" is absent and skipped).
  3. Recursing into "sku": "BK-1042" is a "string" and matches ^[A-Z]{2}-[0-9]{4}$. Recursing into "price": -5 is a "number" (not a bool), fails -5 < 0.5, and appends "price must be >= 0.5".
  4. Finally, because additionalProperties is False, scanning data's keys spots "coupon" outside properties and appends "unexpected property: coupon", returning (False, ["price must be >= 0.5", "unexpected property: coupon"]).

Complexity

  • Time: O(V + K) plus regex matching time, where V is the number of data nodes visited by a schema rule and K is the total number of required entries, properties keys, and object keys inspected across visited objects. At each visited node we perform an O(1) type check and O(1) dictionary lookups (name in value, name in properties); extra nested subtrees under allowed additionalProperties: True keys that have no sub-schema are never even traversed! Regex matching via Python's re module typically runs in O(len(string)) time for simple patterns, though backtracking regexes can degrade exponentially on adversarial inputs (see the ReDoS follow-up below).
  • Space: O(D + E + P), where D is the maximum nesting depth (D <= 20 here, one call-stack frame and short path string per level), E is the number of collected error messages, and P is the number of distinct compiled regex patterns stored in _regex_cache.

Edge cases

  • bool vs int/float: True and False map strictly to "boolean", never "number", and 1 / 0 map strictly to "number", never "boolean".
  • None values and present-vs-missing keys: _json_type(None) returns None, so None fails every typed schema. Crucially, {"a": None} has key "a" present in the dict ("a" in value is True), so a required string field "a" reports "a must be of type string" rather than "missing required property: a".
  • Inclusive numeric bounds: minimum: 0.5 and maximum: 9999 accept exact boundary values 0.5 and 9999 while rejecting 0.49 and 9999.01.
  • Empty containers and schemas without "type": [] satisfies any "array" schema, {} satisfies any "object" schema with no required fields, and {} (the empty schema) accepts every value including None. A schema like {"minimum": 5} with no "type" keyword validates numbers and ignores strings because _validate_node dispatches on actual_type.
  • Non-object roots and 2D arrays: Root primitives and root arrays label their top path "root" ("root must be of type number", "root[1] must be >= 0"), and nested arrays chain brackets cleanly ("matrix[1][2]").
  • Floating-point NaN: Strict JSON (RFC 8259) forbids NaN, though Python's json.loads accepts NaN unless parse_constant rejects it. In IEEE 754 arithmetic, both nan < minimum and nan > maximum evaluate to False; in production, reject non-finite floats up front with math.isnan(value) or math.isinf(value).

Common mistakes

  • Checking isinstance(value, (int, float)) before isinstance(value, bool): Lets {"price": True} sneak past "type": "number" as 1.
  • Continuing keyword validation after a type error: Produces confusing duplicate errors or crashes immediately with TypeError when comparing incompatible Python types ("two" < 1) or calling regex.search(123).
  • Using re.match instead of re.search: Python's re.match anchors at the start of the string only (so pattern [0-9]{3} matches "123abc" yet rejects "abc123", surprising both partial-match and full-match expectations!). Using re.search honors JSON Schema's standard unanchored regex rule while letting ^...$ enforce a full-string match.
  • Treating additionalProperties as False by default: In JSON Schema, extra object keys are allowed unless additionalProperties is explicitly False.
  • Checking required fields with if not value.get(name): Falsely flags 0, False, "", [], {} and None as "missing"! Always check key membership with if name not in value.
  • Validating absent optional properties: Properties listed in properties are optional unless also listed in required.

Alternative approaches

  • Schema compilation into callable validator functions: Instead of reading schema dict keys (schema.get("minimum"), schema.get("type")) on every payload, parse the schema once into a tree of specialized closures or generated Python functions (compile_schema(schema) -> Callable). This eliminates per-request schema dictionary lookups completely.
  • Structured error objects (ValidationError(path, keyword, message)): Returning structured objects internally (and formatting strings at the boundary) lets callers localize error text into other languages or highlight exact form inputs in a UI without parsing strings.

Follow-up questions

  • How would you add local $ref pointer resolution while safely handling recursive or cyclic schemas? Store root_schema at the start of validate and resolve local JSON Pointer strings (RFC 6901 paths like "#" for the root schema or "#/$defs/Node", where ~1 unescapes to / and ~0 unescapes to ~) to their target sub-schema dict. Normal recursive data schemas—such as a folder "Node" whose children array references "#/$defs/Node"—terminate naturally because each step consumes one level of finite input data! The only infinite-loop hazard is a productive-free $ref cycle that never advances deeper into data (such as A -> {"$ref": "#/$defs/B"} and B -> {"$ref": "#/$defs/A"}), which we catch by passing a seen_refs_at_current_value set that resets whenever we step into a child property or array element, raising a ValueError if the same (id(target_schema), path) repeats without moving down the data tree:
def resolve_pointer(root_schema: dict, ref: str) -> dict:
    if ref == "#":
        return root_schema
    if not ref.startswith("#/"):
        raise ValueError(f"unsupported non-local reference: {ref}")
    node = root_schema
    for raw_token in ref[2:].split("/"):
        # Unescape ~1 before ~0 per RFC 6901 so "~01" becomes "~1", not "/".
        token = raw_token.replace("~1", "/").replace("~0", "~")
        node = node[token]
    return node
  • What defenses prevent catastrophic regex backtracking when schemas supply untrusted pattern expressions? ReDoS (catastrophic backtracking) happens when a backtracking regex engine like Python's re evaluates ambiguous nested quantifiers such as ^(a+)+$ against a near-matching string like "a" * 30 + "!", exploring O(2^k) paths and pegging a CPU core for seconds or minutes on a 31-byte string! The gold-standard defense is replacing re with an automaton-based linear-time regex engine such as Google RE2 (google-re2 in Python) or Rust's regex crate (via PyO3), which guarantees O(pattern_len * string_len) worst-case runtime by rejecting backreferences and lookarounds at schema-registration time. Pair that with caps on maximum pattern length (for example, <= 256 chars) and maximum string length (maxLength) before regex evaluation.
  • How could you speed up validation when one fixed schema checks millions of payloads per minute? One million requests per minute is ~16,700 requests/second (~60 microseconds budget on a single core). First, compile each schema once at registration/cache-load time (keyed by (schema_id, version) hash) into flat Python bytecode or a Rust/C extension validator (such as fastjsonschema or pydantic-core), precompiling all regexes and converting required / properties key sets into frozensets upfront. Second, avoid allocating dotted path strings during the happy path—pass lightweight path tokens or integer stack indices and format strings only when an error actually occurs, plus offer a fail_fast=True mode when an API gateway only needs a pass/fail boolean. Finally, because validation is pure CPU work, scale horizontally across multiple worker processes (or GIL-free native workers) rather than CPython threads.

Follow-up questions

Similar questions

More DocuSign interview questions

All 5 DocuSign questions →