Jsontron 0.2 specification

Jsontron is a JSON Schema vocabulary for Schematron-style business rules whose expressions are jq. This document defines what a conforming implementation does. The syntax of the keywords is defined by the meta-schema schemas/jsontron-0.2.json; the conformance suite in tests/ is the executable form of this document.

The words MUST, SHOULD and MAY are used as in RFC 2119.

1. Keywords

Jsontron adds four keywords to a schema object:

Keyword Value Role
rules non-empty array of rule objects assertion
assert assert item, or non-empty array of them assertion, sugar for a context: "." rule
report same shape as assert assertion, inverse of assert
let non-empty object of name → jq expression bindings for the three above

A rule object has a string context, at least one of asserts / reports (non-empty arrays of objects), and optional let and id.

An assert item is an object with a string test and optional message, id, and one of flag or role (setting both is an error). In the assert / report sugar, an item may also be a bare string "<jq>", which stands for { "test": "<jq>" }.

When message is absent, the failure message is the text of test, taken literally.

id, flag and role are strings with at least one non-whitespace character, trimmed of surrounding whitespace. role is an alias of flag. let names match [A-Za-z_][A-Za-z0-9_]* and root is reserved. context, test and let expressions are non-empty.

2. The rule set of a schema object

The four keywords on one schema object form a single rule set, built when the schema is compiled:

  1. Start with the rules of rules, in order (none when rules is absent).
  2. Collect the items of assert as asserts and the items of report as reports.
  3. If there are any, append them to the first rule whose context is exactly the string ".": asserts after that rule's asserts, reports after its reports. If no such rule exists, append a new rule { "context": "." } holding them, with no id and no let.
  4. The schema-level let bindings apply to the whole rule set.

A schema object that has let and none of rules, assert, report has no rule set: its let is checked at build time and never evaluated.

The rule set is evaluated once per instance the schema object is applied to, and produces either a list of failures (possibly empty) or one evaluation error. It is an assertion: the schema object is invalid for that instance when the list is non-empty or there is an error, and it takes part in allOf, anyOf, oneOf, not, if and $ref like any other assertion keyword.

3. Evaluation

Let instance be the value the schema object is applied to and root the whole document being validated.

  1. $root is bound to root in every expression.
  2. Schema-level let: for each binding in document order, evaluate its expression with . = instance; bind $name to the first value it produces, or to null when it produces none. A binding sees $root and the bindings before it.
  3. For each rule, in order:
    1. Evaluate context with . = instance. Each value it produces is a context node. No values means the rule is vacuously satisfied.
    2. For each context node, in order:
      1. Rule-level let: as in step 2, with . = the context node. These bindings are visible to this rule only and shadow schema-level bindings of the same name.
      2. For each assert, then each report, in order: evaluate test with . = the context node. The test is truthy when it produces at least one value and none of its values is false or null. An assert fails when its test is not truthy; a report fails when its test is truthy.
      3. Each failing item adds one failure whose text is its message (section 4).

Rule-level bindings are not visible in context. Every rule runs: there is no shadowing between rules.

Evaluation error. If evaluating a let, context or test expression raises a jq error, evaluation of the rule set stops, failures collected so far are discarded, and the result is a single error carrying the engine's error text. That text is not normative.

4. Messages

An item without message has the text of its test as message: it is not evaluated, so quotes and \(...) in it are kept as written.

Otherwise the message string is turned into a jq expression:

  • If, ignoring leading whitespace, it starts with ", it is used as is.

  • Otherwise it is wrapped as a jq string literal, reading it left to right:

    • a backslash and the character after it are copied unchanged, except that
    • \( starts an interpolation, which is copied unchanged up to its matching ). Matching counts nested parentheses and skips jq string literals inside the interpolation (which may contain interpolations of their own);
    • elsewhere, " becomes \", and newline, carriage return and tab become \n, \r, \t.

    So \(...) interpolation works in plain text, and quotes inside it are jq's own: order \(.id // "?") is "late" becomes "order \(.id // "?") is \"late\"".

It is evaluated with . = the context node and all bindings of the rule in scope. The first value it produces is the message: a string as is, null as the empty string, any other value as its JSON text. If it produces no value or raises an error, the message is the empty string.

The failure text is the message with a prefix built from the labels that are set, in this order, followed by one space: [<rule id>], [<item id>], [flag=<flag or role>]. With no label set there is no prefix and no space.

[orders][high-value-discount][flag=warning] order O-1 discount is below policy

5. Reporting

  • Each failure is reported as its own validation error, in the order produced. An evaluation error is reported as one validation error.
  • The instance location of these errors is the location of instance, the value the schema object is applied to (not the context node).
  • How errors are surfaced otherwise (types, keyword name, schema location) follows the host JSON Schema library.

6. Build time

An implementation MUST reject, when the schema is compiled and before any instance is validated:

  • keyword values that do not match section 1, and
  • any context, test, let or message expression that is not a valid jq program on its own (syntax errors, unknown functions, unknown labels).

Each expression MUST be checked in isolation. Checking only a program assembled from several expressions is not enough, since unbalanced text such as true) , (false can be valid once embedded. An implementation that runs an assembled program (section 7) MUST compile that program at build time as well.

A reference to a variable that is not in scope ($root, an in-scope let, or a binding in the expression itself) fails as an evaluation error under jqlite (which treats unbound $name as a host variable); an implementation backed by an engine that checks variable scope at compile time MAY reject it at build time instead.

7. Reference lowering

The semantics above are equivalent to running one jq program per rule set, with input { "root": <root>, "node": <instance> } and a single output: the array of failure texts. Implementations MAY run this lowered program or evaluate expression by expression with host variables, as long as they pass the suite.

In the templates, ⟨x⟩ is the text of an expression followed by two newlines, so that a trailing jq comment cannot swallow what follows (the second newline ends a comment that a final backslash continues onto the next line), and ⟪s⟫ is s as a JSON string literal.

PROGRAM  :=  .root as $root | .node | LETS [ RULE , RULE , ... ]
LETS     :=  first((⟨let expr⟩), null) as $name |      (once per binding, in order; may be empty)
RULE     :=  ((⟨context⟩) | LETS (ITEM , ITEM , ...))
ITEM     :=  (if TRUTHY then empty else TEXT end)      (assert)
             (if TRUTHY then TEXT else empty end)      (report)
TRUTHY   :=  ([(⟨test⟩)] | length > 0 and all(.[]; . != null and . != false))
TEXT     :=  (⟪prefix⟫ + (try first(((⟨message expr⟩) | STR), "") catch ""))      (item with message)
             ⟪prefix + test text⟫                                                (item without message)
STR      :=  if type == "string" then . elif . == null then "" else tojson end

For this schema object:

{
  "let": { "cap": ".policy.cap" },
  "rules": [ { "id": "orders", "context": ".orders[]",
               "asserts": [ { "test": ".lines <= $cap", "message": "order \\(.id) over cap" } ] } ],
  "report": ".locked"
}

the program is (line breaks inside ⟨x⟩ omitted):

.root as $root | .node | first((.policy.cap), null) as $cap |
[ ((.orders[]) | ((if ([(.lines <= $cap)] | length > 0 and all(.[]; . != null and . != false))
                   then empty
                   else ("[orders] " + (try first((("order \(.id) over cap") | STR), "") catch "")) end))),
  ((.) | ((if ([(.locked)] | length > 0 and all(.[]; . != null and . != false))
           then ".locked"
           else empty end))) ]

A jq error escaping this program is the evaluation error of section 3.

8. Portable jq profile

The reference for expression semantics is jqlite, the portable profile of jq 1.8. Schema authors can rely on the following in every conforming implementation; the suite file tests/jq-profile.json tests them.

  • Paths and iteration: ., .a, .a.b, .["a"], .[n], slices, .[], .., optional ?.
  • Operators: |, ,, arithmetic, comparisons, and / or / not, //.
  • Construction: arrays, objects, string interpolation "\(...)".
  • Control: if / elif / else, try / catch, reduce, foreach, ... as $x, destructuring, def.
  • Builtins: length, keys, has, in, type, select, empty, error, map, map_values, to_entries, from_entries, with_entries, add, any, all, range, first, last, limit, unique, unique_by, group_by, sort, sort_by, min, max, min_by, max_by, contains, inside, index, indices, IN, INDEX, tostring, tonumber, tojson, fromjson, startswith, endswith, ltrimstr, rtrimstr, split, join, ascii_downcase, ascii_upcase, test, match, capture, sub, gsub, floor, ceil, round, sqrt, abs, paths, getpath, flatten, reverse, not, isempty, values, nulls, strings, numbers, booleans, arrays, objects, scalars.

Outside the profile, and not to be relied on:

  • Input, output and environment: input, inputs, debug, stderr, input_filename, $ENV, env, halt, halt_error, $__loc__, modules (import, include), now and the date functions.
  • Regular expression features outside the jqlite regex flavor (no lookaround, backreferences or inline flags; ASCII character classes).
  • Numbers that are not exactly representable as IEEE 754 doubles, and the exact text tojson gives a non-integer number.
  • The text of jq error messages.

9. Versioning

The version of this specification is the version of the meta-schema. Implementations state which specification version they implement; their own package versions are independent of it.