The npm package @devlooped/jsontron adds the Jsontron keywords to Ajv. addJsontron(ajv) registers rules, assert, report and let on an Ajv instance; ajv.compile then checks them and compiles their jq, and their failures come back in validate.errors with those of the standard keywords. jq is evaluated by @devlooped/jqlite, in pure TypeScript, synchronously.
ajv/dist/2020.js), and Ajv's strict mode stays on.specVersion says so.$ npm install ajv @devlooped/jsontron
import Ajv2020 from "ajv/dist/2020.js";
import { addJsontron } from "@devlooped/jsontron";
const ajv = addJsontron(new Ajv2020({ allErrors: true }));
const validate = ajv.compile({
type: "object",
required: ["orders", "policy"],
rules: [
{
context: ".orders[] | select(.total > 1000)",
asserts: [
{
test: ".discount >= $root.policy.minDiscount",
message: "order \\(.id): discount \\(.discount) is below policy",
},
],
},
],
});
const valid = validate({
policy: { minDiscount: 0.1 },
orders: [
{ id: "A-1", total: 2500, discount: 0.05 },
{ id: "A-2", total: 80, discount: 0 },
],
});
console.log(valid); // false
for (const error of validate.errors ?? [])
console.log(`${error.instancePath} ${error.keyword}: ${error.message}`);
rules: order A-1: discount 0.05 is below policy
The rule selects the orders over 1000, so only A-1 is tested. The failure is reported at the location of the instance the schema object applies to, here the root (the empty path), under the keyword rules: see Validation results.
| Page | What it covers |
|---|---|
| Building schemas | addJsontron, compiling, JsontronSchemaError |
| Validation results | the Ajv errors of failures and of evaluation errors |
| API reference | every export of the package |
| Package readme | the readme published with the package |
The keywords themselves are described in the guide.