Katkat

Validate JSON against a protobuf-like schema

Applied IntuitionSoftware Engineer · Technical Screen

Last 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 a dict (for nested messages).
  • required: A boolean indicating if the field must be present.

Input Rules

  • If type is a nested dict, the data for that field must also be a dictionary and must be recursively validated against that nested schema.
  • If a field is required and missing from data, return False.
  • If a field exists in data but its type does not match the schema, return False.
  • Extra fields present in data that 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

  • data will 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, and dict.

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?