Building schemas

Registering the keywords

Jsontron.MetaSchemas.Register();

MetaSchemas.Register does, once per process (further calls only repeat the registrations):

  1. replaces JsonSchema.Net's Dialect.Default (and the dialect of BuildOptions.Default) with the same dialect plus rules, assert, report and let;
  2. registers the Jsontron dialect, its vocabulary and its meta-schema, https://www.schemastore.org/jsontron-0.2.json, in the registries of the build options.

After it, JsonSchema.FromText, JsonSchema.FromFile and JsonSchema.Build pick up the keywords with no other configuration. Call it at startup, before the first schema is built.

To use build options of your own, pass them: their dialect is set to the extended default, and the registries they hold get the dialect, the vocabulary and the meta-schema.

var options = new BuildOptions();
Jsontron.MetaSchemas.Register(options);

var schema = JsonSchema.FromText(text, options);

Declaring the dialect

A schema can declare that it uses Jsontron with $schema. Dialect.Jsontron is draft 2020-12 plus the four keywords, and its identifier is the meta-schema's:

{
  "$schema": "https://www.schemastore.org/jsontron-0.2.json",
  "type": "object",
  "assert": { "test": ".start <= .end", "message": "the period ends before it starts" }
}

Editors that read SchemaStore also check the syntax of the keywords against that meta-schema while you write them.

Build errors

Every Jsontron keyword is checked when the schema is built:

  • its value 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.

A schema that fails either check is not built: JsonSchema.Net throws a JsonSchemaException, whose message says what is wrong.

try
{
    JsonSchema.FromText("""{ "assert": ".total >" }""");
}
catch (JsonSchemaException ex)
{
    Console.WriteLine(ex.Message); // Invalid jq test: Unexpected end of program at line 1, column 9
}

An expression is compiled once, when the schema is built, and reused for every document. An undefined $name is not a build error: it fails when it is evaluated (see jq in Jsontron).