data-to-jsonschema
v1.0.1
Published
Convert plain javascript objects to JSON Schema
Maintainers
Readme
data-to-jsonschema
Convert plain javascript objects to JSON Schema.
Requirements: Node.js 20 or newer. This package is ESM-only —
importonly, norequire.
Installation
npm install data-to-jsonschemaExample
Convert data to JSON Schema
import {
createJsonSchemaValidator,
generateJsonSchemaFromData,
} from "data-to-jsonschema";
const TEST_DATA = [
{
id: 1,
name: "John Doe",
age: 30,
email: "[email protected]",
},
{
id: 1,
name: "John Doe",
age: 30,
email: "[email protected]",
address: {
street: "123 Main St",
city: "Anytown",
state: "NY",
zip: "12345",
},
},
{
id: 1,
name: "John Doe",
age: 30,
email: null,
preferences: [{ name: "pref1", value: "value1" }],
},
];
const jsonSchema = generateJsonSchemaFromData(TEST_DATA, "TestData", {
additionalProperties: false,
});
console.log(JSON.stringify(jsonSchema, null, 2));Create a validator function from the generated schema
const validator = createJsonSchemaValidator(jsonSchema)
console.log(validator({id: 1, name: "John Doe", age: 30, email: "[email protected]"}));
// { valid: true, errors: undefined }
console.log(validator({id: 1, name: "John Doe", age: 30 }));
// { valid: false, errors: [{...}] } — missing required `email`Subpath imports
You can import individual functions from per-feature subpaths if you only need one piece of the library:
import { generateJsonSchemaFromData } from "data-to-jsonschema/generate-schema";
import { createJsonSchemaValidator } from "data-to-jsonschema/validator";
import { traverseObject } from "data-to-jsonschema/traverse";
import type { JsonSchema, JsonType } from "data-to-jsonschema/generate-schema";The bundled barrel (import { ... } from "data-to-jsonschema") continues to work and re-exports everything.
Utilities
generateJsonSchemaFromData(data, title?, opts?)
Infer a JSON Schema (Draft-07) from an array of sample objects. Differing types for the same key become oneOf, array item types are combined via anyOf, and required is the intersection of keys across samples — a property is only required if it appears in every sample.
import { generateJsonSchemaFromData } from "data-to-jsonschema";
generateJsonSchemaFromData(
[{ id: 1, name: "John" }, { id: 2, name: "Jane", age: 30 }],
"User",
{ additionalProperties: false },
);Options:
additionalProperties(boolean, defaultfalse) — allow properties beyond those observed in the samples.existingSchema(JsonSchema & ObjectType) — fold a previously-generated schema into the merge as if it were another sample. Useful for widening a schema across runs.
Returns a JsonSchema & ObjectType. An empty data array yields an empty object schema.
createJsonSchemaValidator(schema)
Generate a function that validates an object against a JSON Schema.
import { createJsonSchemaValidator } from "data-to-jsonschema";
const validator = createJsonSchemaValidator({
type: "object",
properties: {
id: { type: "number" },
name: { type: "string" },
age: { type: "number" },
email: { type: "string" }
},
required: ["id", "name", "age", "email"]
});
validator({
id: 1,
name: "John Doe",
age: 30,
email: "myemail.com"
}); // { valid: true, errors: undefined }
validator({
id: 1,
age: null
}); // { valid: false, errors: [{...}] }traverseObject(obj, callback)
Walk a plain javascript object and call a callback for each primitive leaf value, with its JSON-dot/bracket path and parent metadata.
import { traverseObject } from "data-to-jsonschema";
const obj = {
id: 1,
profile: {
name: "John Doe",
},
tags: ["admin", "owner"],
};
traverseObject(obj, (value, jsonPath, meta) => {
console.log(value, jsonPath, meta);
});
// console output (one line per primitive leaf):
// 1 'id' { key: 'id', parent: { path: '', type: 'object' } }
// 'John Doe' 'profile.name' { key: 'name', parent: { path: 'profile', type: 'object' } }
// 'admin' 'tags[0]' { key: 0, parent: { path: 'tags', type: 'array' } }
// 'owner' 'tags[1]' { key: 1, parent: { path: 'tags', type: 'array' } }The third callback argument meta is optional — drop it if you only need the value and path.
