Ajv 是一个 JSON Schema 验证库,可以用来验证 JSON 数据的格式是否符合指定的规范。Ajv-errors 是一个 Ajv 的插件,用来提供更详细的错误信息。
以下是使用 Ajv 和 Ajv-errors 进行 JSON 数据的验证的示例代码:
安装 Ajv 和 Ajv-errors:
npm install ajv ajv-errors
使用 Ajv 和 Ajv-errors 进行 JSON 数据的验证并提示错误信息:
const Ajv = require('ajv')
const ajv = new Ajv({ allErrors: true })
require('ajv-errors')(ajv)
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name', 'age']
}
const data = {
name: '张三'
}
const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) {
console.log(validate.errors)
}
输出结果如下:
[
{
keyword: 'required',
dataPath: '',
schemaPath: '#/required',
params: { missingProperty: 'age' },
message: "should have required property 'age'"
},
{
keyword: 'type',
dataPath: '.name',
schemaPath: '#/properties/name/type',
params: { type: 'string' },
message: 'should be string'
}
]
可以看到,Ajv-errors 提供了更详细的错误信息,包括所缺少的属性名称和所期望的属性类型。