我想通过AJV-JSON Schema验证或自定义关键字来做的(最好是与此结合):数组可以具有1个或2个JSON对象,类型分别为'admin'和'guest'。 “ type”:“ guest”对象将始终存在,并且“ type”:“ admin”对象是可选的。
额外说明:
-对象本身将来可能包含附加属性和嵌套对象
-其他有效枚举是superadmin,admin,user和guest
-数组中的类型顺序为:superadmin,admin,user和guest。是否可以检查顺序? (尽管它是可选的)
-“ guest”类型的对象将始终存在,并且将存在唯一类型的对象。如果重新出现任何对象类型(例如superadmin,admin,user和guest),则其为错误
//这是模式:
{
"type": "object",
"properties": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": { "enum": ["guest", "admin"]
},
"rights": {"type": "string"},
"hyperLink": {"type": "string", "format": "uri"}
}
}
}
}
我需要在json中的某处添加'checkTypeAndValue'标志,以便我可以获取完整的JSON对象和相应的属性以进行程序化检查?
const checkTypeAndValue = function (schema, completeJSONObj) {
//
};
ajv.addKeyword('checkTypeAndValue', {
validate: checkTypeAndValue,
errors: true
});
这是一些有效和无效的示例:
/Valid 1: As type is 'admin' and so 'rights' SHOULD NOT be in 'guest' object
{
[
{
"type":"admin",
"hyperLink": "http://www.someguest.com",
"rights":"all"
},
{
"type":"guest",
"hyperLink": "http://www.someadmin.com"
}
]
}
//Valid 2: You can have a SINGLE 'guest' object. 'admin' object is not required all the time
{
[
{
"type":"guest",
"hyperLink": "http://www.someadmin.com",
"rights": "limited" //MANDATORY or REQUIRED Attribute
}
]
}
//InValid
{
[
{
"type":"admin",
"hyperLink": "http://www.someguest.com",
"rights":"all"
},
{
"type":"guest",
"hyperLink": "http://www.someadmin.com",
"rights":"limited"
//Error ==> As rights=all is there in 1st object, you cannot set 'rights' to any value including blank even having 'rights' attribute is not valid.
}
]
}
这里是我需要解决的其他条件:
//Assuming admin object exist with rights....
if( type == admin && rights != ""){
if(type == guest && rights attribute is there && rights != ""){
//The 'guest' object will always be there....
//error: guest 'rights' cannot have a value if type is 'admin' and rights is 'all' or any other value.
}
}else{
//Assuming mandatory guest object exist with rights....
if(guest.rights does not exist OR guest.rights == "")
//Error: 'rights' is MANDATORY attribute in guest block and error if its empty
else
//Everything is fine
}
还有什么方法可以检查数组中只有一对特定类型的对象?例如:只有一种“访客”,“管理员”类型。错误,如果“访客”或“管理员”的类型不只一种]
//完整示例
{
[
{
"type":"superadmin",
"hyperLink": "http://www.superadmin.com"
},
{
"type":"admin",
"hyperLink": "http://www.admin.com",
"rights":"all"
},
{
"type":"user",
"hyperLink": "http://www.user.com"
},
{
"type":"guest",
"hyperLink": "http://www.guest.com"
}
]
}
我想通过AJV-JSON Schema验证或自定义关键字来做的(最好是与此结合):数组可以具有1个或2个JSON对象,类型分别为'admin'和'guest'。 “ type”:“ ...
使用JSON模式执行此操作似乎有些棘手,但有可能。