The Schema module provides utilities for converting Zod schemas to JSON Schema objects, useful for generating documentation, API specs, or validation schemas.
Functions
toJsonSchema
Converts a Zod schema to a JSON Schema object, stripping the $schema meta-property.
The Zod schema to convert to JSON Schema format
A JSON Schema object representation of the Zod schema, with the $schema property removed
Usage
import { z } from 'zod'
import { toJsonSchema } from 'incur'
const userSchema = z.object({
name: z.string(),
age: z.number().optional(),
email: z.string().email()
})
const jsonSchema = toJsonSchema(userSchema)
// {
// type: 'object',
// properties: {
// name: { type: 'string' },
// age: { type: 'number' },
// email: { type: 'string', format: 'email' }
// },
// required: ['name', 'email']
// }
Example: Generate OpenAPI Schema
import { z } from 'zod'
import { toJsonSchema } from 'incur'
const requestSchema = z.object({
id: z.string().uuid(),
action: z.enum(['create', 'update', 'delete']),
payload: z.record(z.unknown())
})
const apiSchema = {
openapi: '3.0.0',
paths: {
'/api/action': {
post: {
requestBody: {
content: {
'application/json': {
schema: toJsonSchema(requestSchema)
}
}
}
}
}
}
}
Example: CLI Help Schema
import { z } from 'zod'
import { toJsonSchema } from 'incur'
const argsSchema = z.object({
file: z.string().describe('Input file path'),
output: z.string().optional().describe('Output directory')
})
// Generate schema for auto-documentation
const helpSchema = toJsonSchema(argsSchema)
// Use this to programmatically generate CLI help text