Ajv库在使用“anyOf”时存在验证JSON模式时的问题,尤其是当使用时“required”关键字时。针对这个问题,可以使用以下代码示例进行解决:
首先,需要在“$ref”中创建引用,可以通过“definitions”或“$id”来实现:
{ "$id": "http://example.com/schemas/schema.json", "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "definitions": { "anyOf": { "anyOf": [ {"$ref": "#/$defs/option1"}, {"$ref": "#/$defs/option2"} ] }, "option1": { "type": "object", "required": ["key1"], "properties": { "key1": {"type": "integer"} }, "additionalProperties": false }, "option2": { "type": "object", "required": ["key2"], "properties": { "key2": {"type": "string"} }, "additionalProperties": false } }, "properties": { "param": {"$ref": "#/$defs/anyOf"} }, "required": ["param"] }
在上面的代码示例中,“$defs”是“definitions”的别名,其中“option1”和“option2”分别定义了两个可以选择的选项。通过使用“anyOf”和引用,“param”可以引用“option1”和“option2”中的任何一个,而“required”关键字将确保请求中包含必需的参数。
接下来,可以使用Ajv进行验证:
const Ajv = require('ajv'); const ajv = new Ajv(); require('ajv-keywords')(ajv, ['instanceof']);
// Compiling the schema
const validate = ajv.compile(schema);
const valid = validate(jsonObject);
if (!valid) { console.log(validate.errors); } else { console.log('Valid!'); }
在上面的代码
上一篇:AJV在Nodejs中的验证