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
"type": Expected JSON type—one of"string","number"(intorfloat, neverbool),"boolean","object"(dict), or"array"(list).Nonedoes not match any of these five types.- If
"type"is specified anddatahas 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).
- If
- Numeric bounds (applied to
"number"values):"minimum": inclusive lower bound; ifvalue < minimum, append"<path> must be >= <minimum>"."maximum": inclusive upper bound; ifvalue > maximum, append"<path> must be <= <maximum>".
- 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>".
- Object rules (applied to
"object"values, evaluated in this order):"required": list of property names that must exist as keys indata(key in data; a key whose value isNonecounts 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 indata."additionalProperties": boolean (defaults toTrue). WhenFalse, checked indatadict order: each key indatanot declared in"properties"appends"unexpected property: <child_path>".
- Array rules (applied to
"array"values):"items": sub-schema validated against every list element in index order0, 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
schemais a syntactically valid dictionary whose regex"pattern"strings compile cleanly under Python'sremodule.- Container nesting depth is at most
20levels. datamay containNone,bool,int,float,str,list, anddictvalues.- Remember that
isinstance(True, int)isTruein Python—boolean values must never be accepted as"number", and integers0/1must never be accepted as"boolean".
Step-by-step walkthrough
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) anditems(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.5in Python would raise aTypeError! - Regex
patternmatching: Standard JSON Schema treatspatternas a substring search unless anchored with^and$(notice Example 1 explicitly writesr"^[A-Z]{2}-[0-9]{4}$"). Usingre.searchsupports both anchored full matches and unanchored partial matches. - Deterministic error order inside an object: Check
requiredfirst (in schema list order), then presentproperties(in schema dict order), then unexpected extra properties whenadditionalPropertiesisFalse(in data dict order).
- Path formatting: Top-level object fields use their bare name (
Map Python values to JSON types (and dodge the bool trap)
Python has one famous type-hierarchy gotcha that trips up many candidates:
boolis a subclass ofint.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 passminimum: 0.5! Checkingisinstance(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 NoneNotice what happens to
None:_json_type(None)returnsNone, which does not equal any of the five supported schema type strings, so any typed schema cleanly rejectsNone.Format field paths and dispatch by type
As we walk down nested objects and lists, we pass the current
pathstring (""at the very top) and one sharederrorslist 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 likeroot[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 sprawlingif/elifchain, 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 thanexpected_typemeans an untyped schema like{"minimum": 5}automatically checks numbers (3fails) while leaving strings ("abc"passes) alone—matching real JSON Schema semantics!Validate leaf rules: numbers and regex patterns
Once
_validate_nodereaches_check_number,valueis guaranteed to be a genuineintorfloat(neverboolorstr). Bothminimumandmaximumare inclusive bounds (>=and<=), so an error fires only on strict<or>:- With
minimum: 0.5,0.5is valid and-5triggers"<path> must be >= 0.5". - Checking
minimumandmaximumwith two separateifstatements (rather thanelif) ensures independent rules are always checked cleanly.
For
_check_string, we compile each regex string once and cache the compiled pattern inself._regex_cache, then checkcompiled_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]- With
Validate containers recursively: objects and arrays
Objects have three distinct responsibilities, executed in order:
requiredfields: Every field name inschema.get("required", [])must exist as a key invalue. Always testif name not in value:—neverif value.get(name) is None:—because{"a": None}has key"a"present (with valueNone), so it should get a type error if"a"expects a string, not a"missing required property"error!propertiessub-schemas: For each(name, sub_schema)inproperties, ifname in value, recurse into_validate_node(sub_schema, value[name], _child_path(path, name), errors). Optional properties absent fromvalueare simply skipped.additionalProperties: Defaults toTrue. When explicitlyFalse, any key invaluethat isnot in propertiesappends"unexpected property: <child_path>".
Arrays simply validate each element
itematindexagainstschema["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.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!Put together the complete solution
Here is the full
solution.pywith 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
valueis 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 objectpropertiesand arrayitems.
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:
- At
path = ""(root),datais adict("object"), matchingtype: "object". _check_objectchecksrequired: ["sku", "price"]—both keys exist indata(optional"in_stock"is absent and skipped).- Recursing into
"sku":"BK-1042"is a"string"and matches^[A-Z]{2}-[0-9]{4}$. Recursing into"price":-5is a"number"(not abool), fails-5 < 0.5, and appends"price must be >= 0.5". - Finally, because
additionalPropertiesisFalse, scanningdata's keys spots"coupon"outsidepropertiesand appends"unexpected property: coupon", returning(False, ["price must be >= 0.5", "unexpected property: coupon"]).
Complexity
- Time: O(V + K) plus regex matching time, where
Vis the number of data nodes visited by a schema rule andKis the total number ofrequiredentries,propertieskeys, and object keys inspected across visited objects. At each visited node we perform anO(1)type check andO(1)dictionary lookups (name in value,name in properties); extra nested subtrees under allowedadditionalProperties: Truekeys that have no sub-schema are never even traversed! Regex matching via Python'sremodule typically runs inO(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
Dis the maximum nesting depth (D <= 20here, one call-stack frame and short path string per level),Eis the number of collected error messages, andPis the number of distinct compiled regex patterns stored in_regex_cache.
Edge cases
boolvsint/float:TrueandFalsemap strictly to"boolean", never"number", and1/0map strictly to"number", never"boolean".Nonevalues and present-vs-missing keys:_json_type(None)returnsNone, soNonefails every typed schema. Crucially,{"a": None}has key"a"present in the dict ("a" in valueisTrue), so a required string field"a"reports"a must be of type string"rather than"missing required property: a".- Inclusive numeric bounds:
minimum: 0.5andmaximum: 9999accept exact boundary values0.5and9999while rejecting0.49and9999.01. - Empty containers and schemas without
"type":[]satisfies any"array"schema,{}satisfies any"object"schema with norequiredfields, and{}(the empty schema) accepts every value includingNone. A schema like{"minimum": 5}with no"type"keyword validates numbers and ignores strings because_validate_nodedispatches onactual_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) forbidsNaN, though Python'sjson.loadsacceptsNaNunlessparse_constantrejects it. In IEEE 754 arithmetic, bothnan < minimumandnan > maximumevaluate toFalse; in production, reject non-finite floats up front withmath.isnan(value) or math.isinf(value).
Common mistakes
- Checking
isinstance(value, (int, float))beforeisinstance(value, bool): Lets{"price": True}sneak past"type": "number"as1. - Continuing keyword validation after a
typeerror: Produces confusing duplicate errors or crashes immediately withTypeErrorwhen comparing incompatible Python types ("two" < 1) or callingregex.search(123). - Using
re.matchinstead ofre.search: Python'sre.matchanchors 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!). Usingre.searchhonors JSON Schema's standard unanchored regex rule while letting^...$enforce a full-string match. - Treating
additionalPropertiesasFalseby default: In JSON Schema, extra object keys are allowed unlessadditionalPropertiesis explicitlyFalse. - Checking required fields with
if not value.get(name): Falsely flags0,False,"",[],{}andNoneas "missing"! Always check key membership withif name not in value. - Validating absent optional
properties: Properties listed inpropertiesare optional unless also listed inrequired.
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_schemaat the start ofvalidateand resolve local JSON Pointer strings (RFC 6901 paths like"#"for the root schema or"#/$defs/Node", where~1unescapes to/and~0unescapes to~) to their target sub-schema dict. Normal recursive data schemas—such as a folder"Node"whosechildrenarray references"#/$defs/Node"—terminate naturally because each step consumes one level of finite inputdata! The only infinite-loop hazard is a productive-free$refcycle that never advances deeper intodata(such asA -> {"$ref": "#/$defs/B"}andB -> {"$ref": "#/$defs/A"}), which we catch by passing aseen_refs_at_current_valueset that resets whenever we step into a child property or array element, raising aValueErrorif 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
reevaluates ambiguous nested quantifiers such as^(a+)+$against a near-matching string like"a" * 30 + "!", exploringO(2^k)paths and pegging a CPU core for seconds or minutes on a 31-byte string! The gold-standard defense is replacingrewith an automaton-based linear-time regex engine such as Google RE2 (google-re2in Python) or Rust'sregexcrate (via PyO3), which guaranteesO(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,<= 256chars) 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,700requests/second (~60 microsecondsbudget 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 asfastjsonschemaorpydantic-core), precompiling all regexes and convertingrequired/propertieskey sets intofrozensets upfront. Second, avoid allocating dottedpathstrings during the happy path—pass lightweight path tokens or integer stack indices and format strings only when an error actually occurs, plus offer afail_fast=Truemode 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
- How would you add local $ref pointer resolution while safely handling recursive or cyclic schemas?
- What defenses prevent catastrophic regex backtracking when schemas supply untrusted pattern expressions?
- How could you speed up validation when one fixed schema checks millions of payloads per minute?
Similar questions
- Remove Consecutive Anagram Words
- Collapse Contiguous Integer Runs
- Maximum Connected Land Sum and Coordinates
- Key-Value CRUD Store
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
More DocuSign interview questions
- Collapse Contiguous Integer Runs Easy
- Maximum Connected Land Sum and Coordinates Medium
- Remove Consecutive Anagram Words Medium Pro
- Key-Value CRUD Store Medium Pro