Validate JSON against a protobuf-like schema
Applied IntuitionSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to recursively validate a JSON object against a structured schema definition and handle field presence constraints.
Problem Statement
Given a schema definition and a JSON object, write a function is_valid(schema, data) that returns True if the data conforms to the schema and False otherwise.
Schema Definition
The schema is defined as a dictionary where keys are field names. Each value is a dictionary with:
type: Either"string","int", or adict(for nested messages).required: A boolean indicating if the field must be present.
Input Rules
- If
typeis a nesteddict, thedatafor that field must also be a dictionary and must be recursively validated against that nested schema. - If a field is
requiredand missing fromdata, returnFalse. - If a field exists in
databut its type does not match the schema, returnFalse. - Extra fields present in
datathat are not defined in the schema should be ignored (or considered valid).
Examples
schema = {
"id": {"type": "int", "required": True},
"metadata": {
"type": {
"source": {"type": "string", "required": True}
},
"required": False
}
}
# Returns True
is_valid(schema, {"id": 1, "metadata": {"source": "sensor_a"}})
# Returns False (missing required 'source')
is_valid(schema, {"id": 1, "metadata": {}})
Constraints
datawill always be a dictionary.- The schema structure is a directed acyclic graph (no self-referencing schemas).
- You do not need to validate deep type-checking for types other than
int,str, anddict.
Hints
Hint 1
Use recursion to handle the nested dictionary structure of the schema.
Hint 2
First, iterate through the required fields in the schema to ensure they exist in the input dictionary.
Hint 3
After checking for presence, iterate through the input dictionary and validate the type of each present field against the schema definition.
Follow-up questions
- How would you modify your solution to support 'repeated' fields (lists of a specific type)?
- What changes are needed if the schema could contain circular references (e.g., a node containing a list of itself)?
- How would you provide descriptive error messages indicating exactly which field failed validation instead of just returning a boolean?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.