Problem · String

Nested JSON Schema Validator

Learn this problem
HardPinterest logoPinterestFULLTIMEONSITE INTERVIEW

Problem statement

You are given two strings, schema and document. Each string contains valid JSON from the restricted grammar below. Return true exactly when the complete document matches the schema.

A schema node is one of:

  • "string", "integer", or "boolean" for a primitive JSON value;
  • {"array": childSchema} for an array whose every element matches childSchema;
  • {"object": {"field": fieldSchema, ...}} for an object.

An object matches only when it has exactly the declared fields: every declared field is present and no undeclared field is present. Field order does not matter. An empty array matches any array schema. The document grammar contains strings, integers, booleans, arrays, and objects; it does not contain null or decimal numbers.

The two inputs may contain JSON whitespace. Strings and field names use only letters, digits, spaces, underscores, and hyphens, so escaped characters do not occur. Both inputs are guaranteed to be syntactically valid, every object has unique keys, and schema is a valid schema.

Function

validateNestedJsonSchema(schema: String, document: String) → boolean

Examples

Example 1

schema = "{\"object\":{\"profile\":{\"object\":{\"name\":\"string\",\"active\":\"boolean\"}},\"scores\":{\"array\":\"integer\"}}}"document = "{\"profile\":{\"name\":\"Ada\",\"active\":true},\"scores\":[3,5]}"return = true

Every required field is present with the exact recursive type, and every score is an integer.

Example 2

schema = "{\"object\":{\"profile\":{\"object\":{\"name\":\"string\",\"active\":\"boolean\"}}}}"document = "{\"profile\":{\"name\":\"Ada\",\"active\":\"true\"}}"return = false

The value of active is a string, not a JSON boolean.

Example 3

schema = "{\"object\":{\"user\":{\"object\":{\"id\":\"integer\"}}}}"document = "{\"user\":{\"id\":7,\"name\":\"Lin\"}}"return = false

Object validation is exact, so the undeclared nested field name makes the document invalid.

Constraints

  • 1 <= schema.length, document.length <= 20000
  • The nesting depth of either input is at most 100.
  • The document contains at most 10000 JSON nodes.
  • Every integer is between -10^9 and 10^9, inclusive.
  • Inputs satisfy the restricted, valid JSON guarantees in the statement.

More Pinterest problems

drafts saved locally
public boolean validateNestedJsonSchema(String schema, String document) {
    // Write your code here.
}
schema"{\"object\":{\"profile\":{\"object\":{\"name\":\"string\",\"active\":\"boolean\"}},\"scores\":{\"array\":\"integer\"}}}"
document"{\"profile\":{\"name\":\"Ada\",\"active\":true},\"scores\":[3,5]}"
expectedtrue
checking account