Business rules for JSON Schema
JSON Schema checks the shape of a document: types, required fields, formats. Jsontron adds the rules that cross fields and compare against the rest of the document, as four keywords whose expressions are jq. One specification, one conformance suite, and implementations for .NET, TypeScript and Python.
{
"rules": [ {
"context": ".orders[] | select(.total > 1000)",
"asserts": [ {
"test": ".discount >= $root.policy.minDiscount",
"message": "order \\(.id): discount below policy"
} ]
} ]
}{
"policy": { "minDiscount": 0.1 },
"orders": [
{ "id": "A-1", "total": 2500, "discount": 0.05 },
{ "id": "A-2", "total": 80, "discount": 0 }
]
}order A-1: discount below policy
They sit in any schema object, beside the standard keywords, and take part in allOf, anyOf,
not, if and $ref like any other assertion.
rules
Select nodes with a context expression, then check each one with asserts and reports.
assert
A test that must hold for the value the schema object applies to.
report
The inverse: a test that must not hold, to call out a forbidden state.
let
Variables computed once and used by every test and message of the rules.
Each implementation is a set of real keywords of the most used JSON Schema library of its language, and evaluates jq with jqlite, so a rule gives the same result in all three. Each has its own guide, with the same topics under the same names.
The schema and the document above, in schema and orders, validated from each language.
The schema is the same JSON everywhere.
using Json.Schema;
Jsontron.MetaSchemas.Register(); // once per process: adds the keywords to JsonSchema.Net
var result = schema.Evaluate(orders, new EvaluationOptions { OutputFormat = OutputFormat.List });
foreach (var detail in result.Details ?? [])
if (detail.Errors is { } errors)
foreach (var error in errors.Values)
Console.WriteLine(error); // order A-1: discount below policy
import Ajv2020 from "ajv/dist/2020.js";
import { addJsontron } from "@devlooped/jsontron";
const ajv = addJsontron(new Ajv2020({ allErrors: true }));
const validate = ajv.compile(schema);
if (!validate(orders))
for (const error of validate.errors ?? [])
console.log(error.message); // order A-1: discount below policy
from jsontron import JsontronValidator
JsontronValidator.check_schema(schema) # the shape of the keywords and every jq expression
for error in JsontronValidator(schema).iter_errors(orders):
print(error.message) # order A-1: discount below policy
The keywords are defined once. These pages hold for every implementation, whichever language you validate from.
rules, assert, report and let, with examples.
Specification
The normative text: syntax, merge, evaluation, messages, build-time checks.
The project
How the specification, the suite and the implementations are kept equal.
Jsontron is open source under the MIT license. Its use is subject to the Open Source Maintenance Fee EULA: if you use it to generate revenue, sponsoring is required.