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.
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.
The four keywords on one schema object form a single rule set, built when the schema is compiled:
rules, in order (none when rules is absent).assert as asserts and the items of report as reports.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.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.
Let instance be the value the schema object is applied to and root the whole document being validated.
$root is bound to root in every expression.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.context with . = instance. Each value it produces is a context node.
No values means the rule is vacuously satisfied.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.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.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.
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:
\( 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);" 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
An implementation MUST reject, when the schema is compiled and before any instance is validated:
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.
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.
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.
., .a, .a.b, .["a"], .[n], slices, .[], .., optional ?.|, ,, arithmetic, comparisons, and / or / not, //."\(...)".if / elif / else, try / catch, reduce, foreach, ... as $x,
destructuring, def.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, inputs, debug, stderr, input_filename,
$ENV, env, halt, halt_error, $__loc__, modules (import, include), now and the
date functions.tojson
gives a non-integer number.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.