可以使用 "nullable": true 来标记可选字段,这样在使用 $ref 引用时可以正确地处理可选字段问题,示例如下:
// 定义一个包含可选字段的 JSON Schema const schema = { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": ["number", "null"], "nullable": true } } }
// 定义一个含有 $ref 引用的 JSON Schema { "type": "object", "properties": { "person": { "$ref": "#/definitions/person" }, "phone": { "type": "string" } }, "definitions": { "person": { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": ["number", "null"], "nullable": true } } } } }
// 使用 AJV 检验 const Ajv = require('ajv'); const ajv = new Ajv();
const validatePerson = ajv.compile(schema); const validatePersonWithRef = ajv.compile({ "$async": true, "type": "object", "properties": { "person": { "$ref": "#/definitions/person" }, "phone": { "type": "string" } }, "definitions": { "person": { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": ["number", "null"], "nullable": true } } } } });
const personData = { "name": "Tom", "age": null };
console.log(validatePerson(personData)); // true console.log(validatePersonWithRef({ "person": personData, "phone": "13800138000" })); // true