JSON Schema Generation
Export valrs schemas to JSON Schema format
JSON Schema Generation
valrs schemas can generate JSON Schema definitions for use with other tools, API documentation, and validation systems.
Generating JSON Schema
Use the .toJsonSchema() method to generate JSON Schema from any valrs schema:
Supported Targets
The .toJsonSchema() method accepts an optional target parameter to specify the JSON Schema version:
Draft 2020-12 (Default)
The latest JSON Schema specification. This is the default when no target is specified:
Draft 07
Widely supported older version:
OpenAPI 3.0
For API documentation with OpenAPI/Swagger:
Type Mappings
The following table shows how valrs types map to JSON Schema:
| valrs Type | JSON Schema |
|---|---|
v.string() | { type: 'string' } |
v.number() | { type: 'number' } |
v.boolean() | { type: 'boolean' } |
v.int32() | { type: 'integer', minimum: -2147483648, maximum: 2147483647 } |
v.int64() | { type: 'integer' } |
v.uint32() | { type: 'integer', minimum: 0, maximum: 4294967295 } |
v.uint64() | { type: 'integer', minimum: 0 } |
v.float32() | { type: 'number' } |
v.float64() | { type: 'number' } |
v.literal(value) | { const: value } |
v.literal(null) | { type: 'null' } |
v.enum([...]) | { type: 'string', enum: [...] } |
v.array(T) | { type: 'array', items: T } |
v.object({...}) | { type: 'object', properties: {...}, required: [...] } |
v.record(T) | { type: 'object', additionalProperties: T } |
v.tuple([A, B]) | { type: 'array', prefixItems: [A, B], minItems: 2, maxItems: 2 } |
v.union([A, B]) | { oneOf: [A, B] } |
v.intersection(A, B) | { allOf: [A, B] } |
v.map(K, V) | Array of [key, value] tuples |
v.set(T) | { type: 'array', items: T, uniqueItems: true } |
T.optional() | { oneOf: [T, { type: 'null' }] } |
T.nullable() | { oneOf: [T, { type: 'null' }] } |
Object Schemas
Object schemas include property definitions and required fields:
Strict Mode
Object schemas with .strict() set additionalProperties: false:
Catchall Properties
Object schemas with .catchall() define additionalProperties:
Composite Types
Arrays
Tuples
Unions
Discriminated Unions
Use Cases
OpenAPI Documentation
Generate schemas for your API documentation:
Form Validation Libraries
Some form libraries accept JSON Schema for validation:
Database Schema Generation
Generate schemas for database column definitions:
Advanced: Input vs Output Schemas
For schemas that transform values (where input and output types differ), you can access both input and output JSON Schemas through the Standard Schema interface:
Note: The .toJsonSchema() method returns the input schema. For output schemas, use the ['~standard'].jsonSchema.output() method directly.
Next Steps
- Standard Schema - How valrs implements the spec
- API Reference - Complete API documentation