npm.io
4.0.0 • Published 2 weeks ago

json-schema-walker

Licence
MIT
Version
4.0.0
Deps
2
Size
16 kB
Vulns
0
Weekly
0
Stars
2

JSON Schema Walker

Loosely based on CloudFlare's json schema tools

A system that visits schemas in a JSON Schema document and makes callbacks before visiting each schema's subschemas.

Requires Node.js 20 or later.

Usage

import { Walker } from "json-schema-walker";
const schema = {
  // your json schema
};
const walker = new Walker<T>();
await walker.loadSchema(schema, {
  cloneSchema: true,
  dereference: false,
  dereferenceOptions: {
    dereference: {
      circular: "ignore",
    },
  },
});
const convertSchema = (schema) => {
  // do something with the schema properties
};
await walker.walk(convertSchema, walker.vocabularies.DRAFT_07);
const updatedSchema = walker.rootSchema;

The vocabulary argument defaults to walker.vocabularies.DRAFT_07. Callbacks run synchronously in both walking APIs. Each schema object is visited once per walk, including when objects are shared or circular. Boolean schemas (true and false) are visited at each schema location, so callbacks that modify objects should first check typeof schema === "object".

Circular references

Passing the options

{
  "dereferenceOptions": {
    "dereference": {
      "circular": "ignore"
    }
  }
}

will dereference all non-circular references in your schema.

Synchronous API

For cases where you don't need $ref resolution, you can use the synchronous methods:

import { Walker } from "json-schema-walker";
const schema = {
  // your json schema (without $ref)
};
const walker = new Walker<T>();
walker.loadSchemaSync(schema, {
  cloneSchema: true, // only option available
});
const convertSchema = (schema) => {
  // do something with the schema properties
};
walker.walkSync(convertSchema, walker.vocabularies.DRAFT_07);
const updatedSchema = walker.rootSchema;

Warning: The synchronous methods (loadSchemaSync and walkSync) do not support $ref resolution. Use the async methods if your schema contains references.