我有三个 json 模式定义。客户、地址和联系方式。
客户端.json
{
"$id": "client.json",
"type": "object",
"definitions": {},
"$schema": "http://json-schema.org/draft-06/schema#",
"properties": {
"name": {
"$id": "/properties/name",
"type": "string"
},
"id": {
"$id": "/properties/id",
"type": "integer"
},
"contact": {
"$ref": "contact.json"
},
"address": {
"$ref": "address.json"
}
}
}
地址.json
{
"$id": "address.json",
"type": "array",
"definitions": {},
"$schema": "http://json-schema.org/draft-06/schema#",
"items": {
"$id": "/items",
"type": "object",
"properties": {
"addressId": {
"$id": "/items/properties/addressId",
"type": "integer"
},
"addressName": {
"$id": "/items/properties/addressName",
"type": "string"
}
}
}
}
联系人.json
{
"$id": "contact.json",
"type": "array",
"definitions": {},
"$schema": "http://json-schema.org/draft-06/schema#",
"items": {
"$id": "/items",
"type": "object",
"properties": {
"contactId": {
"$id": "/items/properties/contactId",
"type": "integer"
},
"contactName": {
"$id": "/items/properties/contactName",
"type": "string"
},
"address": {
"$ref": "address.json"
}
}
}
}
待验证对象
var client = {
"name": "test",
"id": 12,
"contact": [
{
"contactId": 12212,
"contactName": "jon",
"address": [
{
"addressId": 64,
"addressName": "pi"
}
]
}
],
"address": [
{"addressId": 4242,
"addressName": "doe"}
]
};
'client.json' 中的 $ref's 工作正常,但从 'contact.json' 引用 'address.json' 时出现错误。在“additionalItems”中使用 $refs 时我没有收到任何错误,但无法针对 $ref 指向的架构进行验证。
我想知道如何使用数组类型模式定义中的 $ref 。另外,我正在使用 AJV 进行模式验证。
编辑 1: AJV 设置
var Ajv = require('ajv');
var ajv = new Ajv({
$data: true,
allErrors: true,
useDefaults: true,
coerceTypes: true,
});
ajv.addSchema(client);
ajv.addSchema(contact);
ajv.addSchema(address);
let valid = ajv.validate('client.json', payload);
if(!valid){
console.log(ajv.errors);
}