Collect Path-Tagged Errors from a Nested Payload Schema Check
Trees & GraphsAuto-graded · 25 test casesLast updated
Recursively walk a JSON-like value alongside a simplified schema and report type and missing-key errors with exact paths, in deterministic order.
Nested Payload Checker
A service receives JSON-like data and must confirm it matches an expected shape before processing it. Your job is to build a small checker that walks a nested value together with a simplified schema and lists every problem it finds.
The value being checked is built only from Python dict, list, str, int, float, bool and None.
The schema
A schema is a dict that may use these keys:
"type": one of"object","array","string","number","boolean","null"."properties": adictmapping key names to sub-schemas. It is meaningful for objects."required": a list of key names that must be present. It is meaningful for objects."items": a single sub-schema that every element of an array must satisfy. It is meaningful for arrays.
How values map to type names
| Python value | Type name |
|---|---|
None | "null" |
bool | "boolean" |
dict | "object" |
list | "array" |
str | "string" |
int or float (not bool) | "number" |
| anything else | "unknown" |
A bool is never a "number", even though Python treats True as an int. An "unknown" value never matches any declared type.
Task
Implement check_payload(data, schema), which returns a list of error strings. If data conforms to schema, return an empty list.
Each error has the form "<path>: <message>".
Paths
- The root value has path
$. - A member
nameof an object at pathPhas pathP.name. - Element number
i(0-based) of an array at pathPhas pathP[i].
For example: $.users[0].name.
Messages
- Type mismatch:
expected <declared type>, got <actual type>. - Missing key:
missing required property '<key>', where<key>is the name from therequiredlist.
Rules for visiting a node
For a value and its schema at some path:
- If the schema has a
"type"and the value's type name differs, record one type-mismatch error for this path and stop. Nothing below this node is examined. - If the schema has no
"type", nothing is checked at this node and nothing below it is examined. - If the type is
"object"and matches:- First, go through
requiredin list order and record a missing-key error for each key not present in the value. - Then go through
propertiesin the schema's own key order. For each declared key that is present in the value, visit the member with its sub-schema. Declared keys that are absent are skipped silently (apart from any missing-key error already recorded). Keys in the value that the schema does not declare are ignored.
- First, go through
- If the type is
"array"and matches, and the schema has"items", visit each element in index order starting at0using theitemsschema. Without"items", elements are not checked. - For other matching types, there is nothing more to do.
Errors appear in the result in the order they are discovered: depth-first, with a node's own missing-key errors first, then each property's entire subtree before the next property, and array elements by ascending index.
Constraints
- The value and schema are finite and nested to a modest depth (recursion is acceptable).
- Schema keys are exactly those listed above; any other keys can be ignored.
- Keys in
requiredandpropertiesare strings. - Object keys in the value are strings.
- A
requiredkey need not appear inproperties; it is then only checked for presence. - An empty array with an
itemsschema produces no errors. - A mismatch at the root yields exactly one error with path
$.
Examples
Example 1
Input: check_payload('101', {'type': 'object', 'required': ['id', 'tags'], 'properties': {'id': {'type': 'number'}, 'tags': {'type': 'array', 'items': {'type': 'string'}}}})
Output: ['$: expected object, got string']
Example 2
Input: check_payload({'id': '101', 'tags': ['pinned', 42]}, {'type': 'object', 'required': ['id', 'tags'], 'properties': {'id': {'type': 'number'}, 'tags': {'type': 'array', 'items': {'type': 'string'}}}})
Output: ['$.id: expected number, got string', '$.tags[1]: expected string, got number']
Example 3
Input: check_payload({'user': {}}, {'type': 'object', 'required': ['user'], 'properties': {'user': {'type': 'object', 'required': ['email']}}})
Output: ['$.user: missing required property \'email\'']
Hints
Hint 1
Write a helper that turns a Python value into one of the six type names, and check for bool before int, since bool is a subclass of int.
Hint 2
Use one recursive function taking the value, its schema and the current path string. Append to a shared list and return immediately after recording a type mismatch.
Hint 3
For objects, emit all missing-key errors first, then loop over the schema's properties in order and recurse only into keys present in the value. For arrays, recurse over indices in ascending order using the path suffix [i].
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the schema and the value as two parallel trees and walk them together with a recursive depth-first function that carries the current path string.
At each node:
- Convert the Python value to a JSON type name. Test
Nonefirst, thenboolbefore the numeric check (otherwiseTruewould be reported as a number), thendict,list,str, and finallyint/float. Anything else is"unknown". - If the schema declares a type and it differs from the value's type, append one mismatch error and return. This stops us from descending into a node whose shape we do not trust.
- If the type is
"object":- Emit a missing-key error for each
requiredkey absent from the value, in list order. - Then iterate
propertiesin insertion order and recurse into each key that exists in the value, extending the path with.key.
- Emit a missing-key error for each
- If the type is
"array"anditemsis given, recurse into each element by ascending index, extending the path with[i].
If the schema has no type, the function does nothing for that node, so keywords such as properties are never applied to a value of unconfirmed shape.
Why it is correct
- The early return on mismatch guarantees that
key in valueis only evaluated on adictandenumerate(value)only on alist, and it produces exactly one error for a mistyped subtree. - Required-key errors are produced before any child is visited, and each child's whole subtree is finished before the next sibling begins. Because Python dicts preserve insertion order and arrays are walked by index, the output order is the deterministic pre-order DFS the statement asks for.
- Absent optional properties are skipped, and undeclared keys in the value are never looked at, matching the rule that extra properties are allowed.
- Putting the
boolcheck ahead of the numeric check implements the "booleans are not numbers" rule.
Complexity
- Time: O(N + S) node and schema-entry visits, plus the cost of building path strings, which is up to O(d) per visited node for depth d. Here N is the number of value nodes reached through declared schema paths and S the total size of the
requiredandpropertiesentries encountered. - Space: O(d) for the recursion stack plus O(E · d) for E error strings.
Reference solution
from typing import Any, List
def check_payload(data: Any, schema: dict) -> List[str]:
problems: List[str] = []
def type_name(value: Any) -> str:
if value is None:
return "null"
if isinstance(value, bool):
return "boolean"
if isinstance(value, dict):
return "object"
if isinstance(value, list):
return "array"
if isinstance(value, str):
return "string"
if isinstance(value, (int, float)):
return "number"
return "unknown"
def walk(value: Any, sub_schema: dict, path: str) -> None:
declared = sub_schema.get("type")
actual = type_name(value)
if declared is not None and actual != declared:
problems.append(f"{path}: expected {declared}, got {actual}")
return
if declared == "object":
for key in sub_schema.get("required", []):
if key not in value:
problems.append(f"{path}: missing required property '{key}'")
for key, child_schema in sub_schema.get("properties", {}).items():
if key in value:
walk(value[key], child_schema, f"{path}.{key}")
elif declared == "array":
item_schema = sub_schema.get("items")
if item_schema is not None:
for i, element in enumerate(value):
walk(element, item_schema, f"{path}[{i}]")
walk(data, schema, "$")
return problems