JSON Schema
JSON Schema (https://json-schema.org/) defines the structure and validation rules for JSON documents. It serves as documentation and aids in code generation (e.g., user interfaces).
Example:
{
"type": "object",
"properties": {
"firstName": {"type": "string"},
"lastName": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["firstName", "lastName"]
}
Validation
Ajv (https://ajv.js.org/) is a popular JSON schema validator.
const Ajv = require("ajv")
const data = { firstName: "foo" }
const ajv = new Ajv()
const validate = ajv.compile(schema) // Use schema from the example above
const valid = validate(data)
if (!valid) {
console.error(validate.errors)
}
JSON Schema Builders
JSON Schema can be verbose to write manually, schema builders can simplify the process. Here’s how to write a schema using TypeBox:
import { Type, Static } from '@sinclair/typebox'
const T = Type.Object({
x: Type.Number(),
y: Type.Number(),
z: Type.Number()
})
This is equivalent to:
const T = {
type: 'object',
required: ['x', 'y', 'z'],
properties: {
x: { type: 'number' },
y: { type: 'number' },
z: { type: 'number' }
}
}
You also get type for free:
type T = Static<typeof T>
// gives you:
type T = {
x: number,
y: number,
z: number
}