Jsontron for TypeScript

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.

Requirements

  • Node.js 20 or later, or a modern browser. The package is ESM only and ships its type declarations.
  • Ajv 8, a peer dependency. Jsontron is written for draft 2020-12 (ajv/dist/2020.js), and Ajv's strict mode stays on.
  • The package implements the Jsontron 0.2 specification; specVersion says so.

Getting it

$ npm install ajv @devlooped/jsontron

A first example

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.

In this section

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.