or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-json-schema-traverse

Traverse JSON Schema passing each schema object to callback

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/json-schema-traverse@1.0.x

To install, run

npx @tessl/cli install tessl/npm-json-schema-traverse@1.0.0

index.mddocs/

JSON Schema Traverse

JSON Schema Traverse is a lightweight JavaScript utility library that provides systematic traversal of JSON Schema objects. It recursively visits each schema node, executing user-defined callback functions with rich contextual information including JSON pointers, parent relationships, and schema hierarchy.

Package Information

  • Package Name: json-schema-traverse
  • Package Type: npm
  • Language: JavaScript (with TypeScript definitions)
  • Installation: npm install json-schema-traverse

Core Imports

const traverse = require('json-schema-traverse');

For ES modules with TypeScript:

import traverse from 'json-schema-traverse';

Basic Usage

const traverse = require('json-schema-traverse');

const schema = {
  properties: {
    name: { type: 'string' },
    age: { type: 'integer' },
    address: {
      type: 'object',
      properties: {
        street: { type: 'string' },
        city: { type: 'string' }
      }
    }
  }
};

// Simple callback traversal
traverse(schema, (schema, jsonPtr, rootSchema) => {
  console.log(`Visiting: ${jsonPtr}`);
  console.log('Schema:', schema);
});

// Pre/post order traversal
traverse(schema, {
  cb: {
    pre: (schema, jsonPtr) => console.log(`Entering: ${jsonPtr}`),
    post: (schema, jsonPtr) => console.log(`Exiting: ${jsonPtr}`)
  }
});

Capabilities

Main Traverse Function

Traverses a JSON Schema object recursively, calling a callback function for each schema node encountered.

/**
 * Traverses a JSON Schema object recursively
 * @param {SchemaObject} schema - The JSON Schema object to traverse
 * @param {Options} opts - Configuration options for traversal
 * @param {Callback} [cb] - Optional callback function (can be provided in opts)
 */
function traverse(schema, opts, cb);

/**
 * Legacy signature for backward compatibility
 * @param {SchemaObject} schema - The JSON Schema object to traverse  
 * @param {Callback} cb - Callback function to execute for each schema node
 */
function traverse(schema, cb);

Callback Function Signature

The callback function receives detailed context about each visited schema node.

/**
 * Callback function executed for each schema node during traversal
 * @param {SchemaObject} schema - Current schema object being visited
 * @param {string} jsonPtr - JSON Pointer path from root to current schema
 * @param {SchemaObject} rootSchema - The original root schema object
 * @param {string} [parentJsonPtr] - JSON Pointer path to parent schema
 * @param {string} [parentKeyword] - Keyword containing this schema (e.g., 'properties', 'items')
 * @param {SchemaObject} [parentSchema] - Parent schema object
 * @param {string|number} [keyIndex] - Property name or array index in parent
 */
type Callback = (
  schema: SchemaObject,
  jsonPtr: string,
  rootSchema: SchemaObject,
  parentJsonPtr?: string,
  parentKeyword?: string,
  parentSchema?: SchemaObject,
  keyIndex?: string | number
) => void;

Pre/Post Order Callbacks

For advanced traversal patterns, callbacks can be provided as an object with separate pre and post functions.

/**
 * Pre/post callback configuration object
 */
interface CallbackConfig {
  /** Called before traversing child elements */
  pre?: Callback;
  /** Called after all child elements have been traversed */
  post?: Callback;
}

Options Configuration

Configuration object to control traversal behavior.

/**
 * Configuration options for schema traversal
 */
interface Options {
  /** 
   * Whether to traverse objects in unknown keywords
   * When true, traverses schema objects in keywords not recognized by JSON Schema
   */
  allKeys?: boolean;
  
  /** Callback function or callback configuration object */
  cb?: Callback | CallbackConfig;
}

Static Keyword Maps

The traverse function exposes static properties that define which JSON Schema keywords are processed during traversal.

/** Keywords containing single schema objects */
traverse.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true,
  if: true,
  then: true,
  else: true
};

/** Keywords containing arrays of schema objects */  
traverse.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};

/** Keywords containing objects with schema properties */
traverse.propsKeywords = {
  $defs: true,
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};

/** Keywords to skip during traversal (non-schema keywords) */
traverse.skipKeywords = {
  default: true,
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};

Types

/**
 * JSON Schema object interface
 */
interface SchemaObject {
  /** Optional schema identifier */
  $id?: string;
  /** Optional schema version */
  $schema?: string;
  /** Allow any additional properties */
  [x: string]: any;
}

Advanced Usage Examples

Collecting All Schema Types

const traverse = require('json-schema-traverse');

const schema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    items: {
      type: 'array',
      items: { type: 'number' }
    }
  }
};

const types = [];
traverse(schema, (schema) => {
  if (schema.type) {
    types.push(schema.type);
  }
});

console.log(types); // ['object', 'string', 'array', 'number']

Building Schema Path Map

const traverse = require('json-schema-traverse');

const pathMap = new Map();

traverse(schema, (schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword) => {
  pathMap.set(jsonPtr, {
    schema,
    parentKeyword,
    parentPtr: parentJsonPtr
  });
});

// Access schema at specific path
const nameSchema = pathMap.get('/properties/name');

Traversing Unknown Keywords

const schema = {
  customKeyword: {
    type: 'string',
    description: 'Custom schema'
  }
};

// Without allKeys, only visits root schema
traverse(schema, (schema, jsonPtr) => {
  console.log(`Visited: ${jsonPtr}`);
});
// Output: "Visited: "

// With allKeys, visits custom keyword schemas  
traverse(schema, { allKeys: true }, (schema, jsonPtr) => {
  console.log(`Visited: ${jsonPtr}`);
});
// Output: 
// "Visited: "
// "Visited: /customKeyword"

Error Handling

The traverse function expects well-formed schema objects. It will silently skip:

  • Non-object values (except at the root level)
  • Array values (unless they are arrays of schemas in array keywords)
  • Schema references ($ref) are passed through as-is without resolution