重要前提
安装AI Skills的关键前提是:必须科学上网,且开启TUN模式,这一点至关重要,直接决定安装能否顺利完成,在此郑重提醒三遍:科学上网,科学上网,科学上网。查看完整安装教程 →
validating-json-data by zaggino/z-schema
npx skills add https://github.com/zaggino/z-schema --skill validating-json-dataz-schema 根据 JSON Schema(草案-04、草案-06、草案-07、草案-2019-09、草案-2020-12)验证 JSON 数据。默认草案:draft-2020-12。
import ZSchema from 'z-schema';
const validator = ZSchema.create();
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer', minimum: 0 },
},
required: ['name'],
};
// 数据无效时抛出异常
validator.validate({ name: 'Alice', age: 30 }, schema);
安装:npm install z-schema
z-schema 基于两个开关 async 和 safe 有四种模式。选择适合用例的模式。
| 模式 | 工厂调用 | 返回值 | 使用场景 |
|---|---|---|---|
| 同步抛出 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
ZSchema.create() |
true 或抛出 ValidateError |
| 默认模式 —— 简单脚本和中间件 |
| 同步安全 | ZSchema.create({ safe: true }) | { valid, err? } | 无需 try/catch 即可检查错误 |
| 异步抛出 | ZSchema.create({ async: true }) | Promise<true> 或拒绝 | 使用异步格式验证器 |
| 异步安全 | ZSchema.create({ async: true, safe: true }) | Promise<{ valid, err? }> | 异步 + 非抛出 |
import ZSchema from 'z-schema';
const validator = ZSchema.create();
try {
validator.validate(data, schema);
} catch (err) {
// err 是 ValidateError
console.log(err.details); // SchemaErrorDetail[]
}
const validator = ZSchema.create({ safe: true });
const result = validator.validate(data, schema);
if (!result.valid) {
console.log(result.err?.details);
}
或者在常规(抛出)验证器上调用 .validateSafe() 以获得相同的结果结构:
const validator = ZSchema.create();
const { valid, err } = validator.validateSafe(data, schema);
使用异步格式验证器时需要。
const validator = ZSchema.create({ async: true });
try {
await validator.validate(data, schema);
} catch (err) {
console.log(err.details);
}
const validator = ZSchema.create({ async: true, safe: true });
const { valid, err } = await validator.validate(data, schema);
ValidateError 包含 .details —— 一个 SchemaErrorDetail 数组:
interface SchemaErrorDetail {
message: string; // "期望类型 string 但找到类型 number"
code: string; // "INVALID_TYPE"
params: (string | number | Array<string | number>)[];
path: string | Array<string | number>; // "#/age" 或 ["age"]
keyword?: string; // "type", "required", "minLength" 等
inner?: SchemaErrorDetail[]; // 来自 anyOf/oneOf/not 的子错误
schemaPath?: Array<string | number>;
schemaId?: string;
}
组合器(anyOf、oneOf、not)会产生嵌套的 inner 错误:
const { valid, err } = validator.validateSafe(data, schema);
if (!valid && err) {
for (const detail of err.details) {
console.log(`${detail.path}: [${detail.code}] ${detail.message}`);
if (detail.inner) {
for (const sub of detail.inner) {
console.log(` └─ ${sub.path}: [${sub.code}] ${sub.message}`);
}
}
}
}
将 ValidateOptions 作为第三个参数传递,以包含或排除特定的错误代码:
// 仅报告类型错误
validator.validate(data, schema, { includeErrors: ['INVALID_TYPE'] });
// 抑制字符串长度错误
validator.validate(data, schema, { excludeErrors: ['MIN_LENGTH', 'MAX_LENGTH'] });
完整的错误代码列表,请参阅 references/error-codes.md。
在启动时编译模式以获得更好的运行时性能并解析交叉引用:
const validator = ZSchema.create();
const schemas = [
{
id: 'address',
type: 'object',
properties: { city: { type: 'string' }, zip: { type: 'string' } },
required: ['city'],
},
{
id: 'person',
type: 'object',
properties: {
name: { type: 'string' },
home: { $ref: 'address' },
},
required: ['name'],
},
];
// 编译所有模式(验证它们并注册引用)
validator.validateSchema(schemas);
// 使用已编译的模式 ID 验证数据
validator.validate({ name: 'Alice', home: { city: 'Paris' } }, 'person');
ZSchema.setRemoteReference('http://example.com/schemas/address.json', addressSchema);
// 或按实例:
validator.setRemoteReference('http://example.com/schemas/person.json', personSchema);
import fs from 'node:fs';
import path from 'node:path';
ZSchema.setSchemaReader((uri) => {
const filePath = path.resolve(__dirname, 'schemas', uri + '.json');
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
});
const { valid, err } = validator.validateSafe(data, schema);
if (!valid && err) {
const missing = validator.getMissingReferences(err);
const remote = validator.getMissingRemoteReferences(err);
}
ZSchema.registerFormat('postal-code', (value) => {
return typeof value === 'string' && /^\d{5}(-\d{4})?$/.test(value);
});
const validator = ZSchema.create();
validator.registerFormat('postal-code', (value) => {
return typeof value === 'string' && /^\d{5}(-\d{4})?$/.test(value);
});
const validator = ZSchema.create({
customFormats: {
'postal-code': (value) => typeof value === 'string' && /^\d{5}(-\d{4})?$/.test(value),
},
});
返回 Promise<boolean>。需要 { async: true }。
const validator = ZSchema.create({ async: true });
validator.registerFormat('user-exists', async (value) => {
if (typeof value !== 'number') return false;
const user = await db.findUser(value);
return user != null;
});
const formats = ZSchema.getRegisteredFormats();
如果模式针对特定版本,请明确设置草案:
const validator = ZSchema.create({ version: 'draft-07' });
有效值:'draft-04'、'draft-06'、'draft-07'、'draft2019-09'、'draft2020-12'(默认)、'none'。
有关各草案之间的功能比较,请参阅 references/draft-comparison.md。
| 选项 | 默认值 | 用途 |
|---|---|---|
breakOnFirstError | false | 在第一个错误处停止验证 |
noEmptyStrings | false | 拒绝空字符串作为类型 string |
noEmptyArrays | false | 拒绝空数组作为类型 array |
strictMode | false | 一次性启用所有严格检查 |
ignoreUnknownFormats | false | 抑制未知格式错误(现代草案始终忽略) |
formatAssertions | null | null=始终断言,true=遵循词汇表,false=仅注释 |
reportPathAsArray | false | 将错误路径报告为数组而非 JSON Pointer 字符串 |
完整的选项参考,请参阅 references/options.md。
针对模式内的特定路径:
validator.validate(carData, fullSchema, { schemaPath: 'definitions.car' });
<script src="node_modules/z-schema/umd/ZSchema.min.js"></script>
<script>
var validator = ZSchema.create();
try {
validator.validate({ name: 'test' }, { type: 'object' });
} catch (err) {
console.log(err.details);
}
</script>
所有类型都从包中导出:
import type {
JsonSchema, // 模式类型(所有草案的联合)
ZSchemaOptions, // 配置选项
ValidateOptions, // 每次调用的选项(schemaPath, includeErrors, excludeErrors)
ValidateResponse, // { valid: boolean, err?: ValidateError }
SchemaErrorDetail, // 单个错误详情
ErrorCode, // 错误代码字符串字面量类型
FormatValidatorFn, // (input: unknown) => boolean | Promise<boolean>
SchemaReader, // (uri: string) => JsonSchema
} from 'z-schema';
import { ValidateError } from 'z-schema';
ZSchema.create(options?) —— 切勿使用 new ZSchema()。工厂函数返回正确类型的变体。.details(而非 .errors)。import type { ... } 导入类型,使用 import { ValidateError } 导入值。draft2020-12。如果针对较旧的草案,请明确指定。每周安装次数
56
代码仓库
GitHub 星标数
342
首次出现
2026年2月27日
安全审计
安装于
github-copilot56
opencode16
gemini-cli16
codex16
kimi-cli16
amp16
z-schema validates JSON data against JSON Schema (draft-04, draft-06, draft-07, draft-2019-09, draft-2020-12). Default draft: draft-2020-12.
import ZSchema from 'z-schema';
const validator = ZSchema.create();
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer', minimum: 0 },
},
required: ['name'],
};
// Throws on invalid data
validator.validate({ name: 'Alice', age: 30 }, schema);
Install: npm install z-schema
z-schema has four modes based on two toggles: async and safe. Pick the one that fits the use case.
| Mode | Factory call | Returns | Use when |
|---|---|---|---|
| Sync throw | ZSchema.create() | true or throws ValidateError | Default — simple scripts and middleware |
| Sync safe | ZSchema.create({ safe: true }) | { valid, err? } | Need to inspect errors without try/catch |
| Async throw | ZSchema.create({ async: true }) | Promise<true> or rejects | Using async format validators |
| Async safe |
import ZSchema from 'z-schema';
const validator = ZSchema.create();
try {
validator.validate(data, schema);
} catch (err) {
// err is ValidateError
console.log(err.details); // SchemaErrorDetail[]
}
const validator = ZSchema.create({ safe: true });
const result = validator.validate(data, schema);
if (!result.valid) {
console.log(result.err?.details);
}
Or call .validateSafe() on a regular (throwing) validator for the same result shape:
const validator = ZSchema.create();
const { valid, err } = validator.validateSafe(data, schema);
Required when using async format validators.
const validator = ZSchema.create({ async: true });
try {
await validator.validate(data, schema);
} catch (err) {
console.log(err.details);
}
const validator = ZSchema.create({ async: true, safe: true });
const { valid, err } = await validator.validate(data, schema);
ValidateError has .details — an array of SchemaErrorDetail:
interface SchemaErrorDetail {
message: string; // "Expected type string but found type number"
code: string; // "INVALID_TYPE"
params: (string | number | Array<string | number>)[];
path: string | Array<string | number>; // "#/age" or ["age"]
keyword?: string; // "type", "required", "minLength", etc.
inner?: SchemaErrorDetail[]; // sub-errors from anyOf/oneOf/not
schemaPath?: Array<string | number>;
schemaId?: string;
}
Combinators (anyOf, oneOf, not) produce nested inner errors:
const { valid, err } = validator.validateSafe(data, schema);
if (!valid && err) {
for (const detail of err.details) {
console.log(`${detail.path}: [${detail.code}] ${detail.message}`);
if (detail.inner) {
for (const sub of detail.inner) {
console.log(` └─ ${sub.path}: [${sub.code}] ${sub.message}`);
}
}
}
}
Pass ValidateOptions as the third argument to include or exclude specific error codes:
// Only report type errors
validator.validate(data, schema, { includeErrors: ['INVALID_TYPE'] });
// Suppress string-length errors
validator.validate(data, schema, { excludeErrors: ['MIN_LENGTH', 'MAX_LENGTH'] });
For the full error code list, see references/error-codes.md.
Compile schemas at startup for better runtime performance and to resolve cross-references:
const validator = ZSchema.create();
const schemas = [
{
id: 'address',
type: 'object',
properties: { city: { type: 'string' }, zip: { type: 'string' } },
required: ['city'],
},
{
id: 'person',
type: 'object',
properties: {
name: { type: 'string' },
home: { $ref: 'address' },
},
required: ['name'],
},
];
// Compile all schemas (validates them and registers references)
validator.validateSchema(schemas);
// Validate data using a compiled schema ID
validator.validate({ name: 'Alice', home: { city: 'Paris' } }, 'person');
ZSchema.setRemoteReference('http://example.com/schemas/address.json', addressSchema);
// or per-instance:
validator.setRemoteReference('http://example.com/schemas/person.json', personSchema);
import fs from 'node:fs';
import path from 'node:path';
ZSchema.setSchemaReader((uri) => {
const filePath = path.resolve(__dirname, 'schemas', uri + '.json');
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
});
const { valid, err } = validator.validateSafe(data, schema);
if (!valid && err) {
const missing = validator.getMissingReferences(err);
const remote = validator.getMissingRemoteReferences(err);
}
ZSchema.registerFormat('postal-code', (value) => {
return typeof value === 'string' && /^\d{5}(-\d{4})?$/.test(value);
});
const validator = ZSchema.create();
validator.registerFormat('postal-code', (value) => {
return typeof value === 'string' && /^\d{5}(-\d{4})?$/.test(value);
});
const validator = ZSchema.create({
customFormats: {
'postal-code': (value) => typeof value === 'string' && /^\d{5}(-\d{4})?$/.test(value),
},
});
Return Promise<boolean>. Requires { async: true }.
const validator = ZSchema.create({ async: true });
validator.registerFormat('user-exists', async (value) => {
if (typeof value !== 'number') return false;
const user = await db.findUser(value);
return user != null;
});
const formats = ZSchema.getRegisteredFormats();
Set the draft explicitly if the schema targets a specific version:
const validator = ZSchema.create({ version: 'draft-07' });
Valid values: 'draft-04', 'draft-06', 'draft-07', 'draft2019-09', 'draft2020-12' (default), 'none'.
For a feature comparison across drafts, see references/draft-comparison.md.
| Option | Default | Purpose |
|---|---|---|
breakOnFirstError | false | Stop validation at the first error |
noEmptyStrings | false | Reject empty strings as type string |
noEmptyArrays | false | Reject empty arrays as type |
For the full options reference, see references/options.md.
Target a specific path within a schema:
validator.validate(carData, fullSchema, { schemaPath: 'definitions.car' });
<script src="node_modules/z-schema/umd/ZSchema.min.js"></script>
<script>
var validator = ZSchema.create();
try {
validator.validate({ name: 'test' }, { type: 'object' });
} catch (err) {
console.log(err.details);
}
</script>
All types are exported from the package:
import type {
JsonSchema, // Schema type (all drafts union)
ZSchemaOptions, // Configuration options
ValidateOptions, // Per-call options (schemaPath, includeErrors, excludeErrors)
ValidateResponse, // { valid: boolean, err?: ValidateError }
SchemaErrorDetail, // Individual error detail
ErrorCode, // Error code string literal type
FormatValidatorFn, // (input: unknown) => boolean | Promise<boolean>
SchemaReader, // (uri: string) => JsonSchema
} from 'z-schema';
import { ValidateError } from 'z-schema';
ZSchema.create(options?) — never new ZSchema(). The factory returns the correctly typed variant..details (not .errors).import type { ... } and values with import { ValidateError }.draft2020-12. Specify explicitly if targeting an older draft.Weekly Installs
56
Repository
GitHub Stars
342
First Seen
Feb 27, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
github-copilot56
opencode16
gemini-cli16
codex16
kimi-cli16
amp16
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
125,600 周安装
ZSchema.create({ async: true, safe: true }) |
Promise<{ valid, err? }> |
| Async + non-throwing |
arraystrictMode | false | Enable all strict checks at once |
ignoreUnknownFormats | false | Suppress unknown format errors (modern drafts always ignore) |
formatAssertions | null | null=always assert, true=respect vocabulary, false=annotation-only |
reportPathAsArray | false | Report error paths as arrays instead of JSON Pointer strings |