Some very simple helper functions for writing concise JSON Schema β perfect for OpenAI Structured Outputs.
import { object, string, number, array, nullable } from 'json-schema-kit'
object({
name: string(),
price: number({ minimum: 0 }),
description: nullable(string()),
categories: array(string()),
})
All functions just return plain JavaScript objects. Freely modify or extend them to fit your needs.
npm install json-schema-kit
Traditional JSON Schema
{
"type": "object",
"properties": {
"name": { "type": "string" },
"price": { "type": "number", "description": "Price in dollars" },
"discount": { "anyOf": [{ "type": "number" }, { "type": "null" }] },
"categories": { "type": "array", "items": { "type": "string", "enum": ["electronics", "clothing", "books"] } },
"dimensions": {
"type": "object",
"properties": {
"width": { "type": "number" },
"height": { "type": "number" }
},
"required": ["width", "height"],
"additionalProperties": false
}
},
"required": ["name", "price", "discount", "categories", "dimensions"],
"additionalProperties": false
}
Using JSON Schema Kit
object({
name: string(),
price: number({ description: 'Price in dollars' }),
discount: nullable(number()),
categories: array(string({ enum: ['electronics', 'clothing', 'books'] })),
dimensions: object({
width: number(),
height: number(),
}),
})
JSON Schema Kit is perfectly suited for OpenAI's Structured Outputs.
For example, here's how to use it with the Vercel AI SDK:
const schema = object({
summary: string(),
sentiment: string({ enum: ['positive', 'neutral', 'negative'] }),
})
await generateObject({
model: openai(...),
schema: jsonSchema(schema),
prompt: 'Analyze this review: "Great product, works perfectly!"',
})
Use $ref
to create reusable schema definitions and reference them throughout your schema:
const person = object({
name: string(),
age: number(),
})
const team = object({
leader: $ref('person'),
members: array($ref('person')),
})
team.$defs = { person }
Read more about
$ref
and$defs
in the JSON Schema Documentation
Create union types using anyOf
to allow multiple possible schemas:
const contact = anyOf([
object({ email: string() }),
object({ phone: string() }),
])
Read more about
anyOf
in the JSON Schema Documentation
Great question! Zod is a versatile and comprehensive library, spanning thousands of lines of code. However, it's not specifically built for generating JSON Schemas, which can lead to unexpected results during conversion. In contrast, JSON Schema Kit provides full control β all in under 100 lines of code.