Building schemas

The validator class

JsontronValidator is jsonschema.Draft202012Validator with the four keywords. It is used as any jsonschema validator class: check_schema, iter_errors, validate, is_valid, and jsonschema.validate(document, schema, cls=JsontronValidator).

$root is the document given to iter_errors, validate or is_valid, also in the schema objects that jsonschema reaches through properties, items, $ref and the applicators. A subschema that declares the draft 2020-12 $schema keeps the Jsontron keywords.

Other validator classes

jsontron.extend(validator_class) returns a new class: validator_class with the four keywords. To combine them with keywords of your own, extend last:

from jsonschema import Draft202012Validator, validators
import jsontron

Validator = jsontron.extend(validators.extend(Draft202012Validator, {"myKeyword": my_keyword}))

A class made the other way round, with validators.extend(JsontronValidator, ...), loses what finds the document for $root.

Checking a schema

JsontronValidator.check_schema(schema) checks the schema against the draft 2020-12 meta-schema, then the Jsontron keywords of every schema object in it:

  • their values must match the syntax of the keywords (a test that is not a string, a blank id, a let named root, both flag and role on an item...);
  • every context, test, let and message expression must compile as jq on its own.

It raises jsonschema.exceptions.SchemaError for the first invalid one, with its schema location. jsontron.check_jsontron(schema) runs the Jsontron part alone.

from jsonschema.exceptions import SchemaError

try:
    JsontronValidator.check_schema({"assert": ".total >"})
except SchemaError as error:
    print(error.message)
Invalid jq in assert/report.asserts[0].test: '.total >': Unexpected end of program at line 1, column 9 (schema location '/')

A schema used without check_schema raises the same SchemaError when its invalid schema object is first applied.

An undefined $name is not a build error: it fails when it is evaluated (see jq in Jsontron).

Compilation

Each schema object with a rule set is lowered to one jq program (ยง7 of the specification) when it is checked or first applied, and the program is cached and reused for every document. Changing a schema object in place afterwards has no effect. The whole document is handed to jq only when an expression reads $root.