json-schema-kit
v0.3.0
Published
Some (very) simple helper functions for writing concise JSON Schema — perfect for OpenAI Structured Outputs.
Maintainers
Readme
🧰 JSON Schema Kit
Some very simple helper functions for writing concise JSON Schema — perfect for OpenAI Structured Outputs.
✨ Quick Taste
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.
🚀 Installation
npm install json-schema-kit🆚 Comparison
{
"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
}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(),
}),
})🤖 OpenAI Structured Outputs
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!"',
})🔗 Using References
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
$refand$defsin the JSON Schema Documentation
🔀 Using Union Types
Create union types using anyOf to allow multiple possible schemas:
const contact = anyOf([
object({ email: string() }),
object({ phone: string() }),
])Read more about
anyOfin the JSON Schema Documentation
🤔 "But what about Zod?"
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.
