问题描述
{
"policyHolder": {
"fullName": "A"
},
"traveller": [
{
"fullName": "B",
"relationship": "Spouse"
},
{
"fullName": "A",
"relationship": "My Self"
}
]
}
在上面的json中,我要验证
In above json, I want to validate that
-
if "relationship" = "My Self"
,然后fullName
必须与policyHolder
中的 -
traveller
数组中必须存在字段relationship
,否则json无效
fullName
相匹配if "relationship" = "My Self"
thenfullName
must match thefullName
inpolicyHolder
- A field
relationship
must exist intraveller
array, else json is invalid
我试图用if-else
,allOf
等创建一个json模式,但是没有任何方法可以进行这些验证,但无法进行.请帮忙!
I have tried to create a json schema with if-else
, allOf
, etc. but nothing works which can do these validations but not able to.Please help!!
模式:
{
"type": "object",
"required": [
"policyHolder",
"traveller",
],
"properties": {
"policyHolder": {
"$id": "#/properties/policyHolder",
"type": "object",
"required": [
"fullName"
],
"properties": {
"fullName": {
"$id": "#/properties/policyHolder/properties/fullName",
"type": "string",
}
}
},
"traveller": {
"$id": "#/properties/traveller",
"type": "array",
"minItems": 1,
"items": {
"$id": "#/properties/traveller/items",
"type": "object",
"properties": {
"fullName": {
"$ref": "#/properties/policyHolder/properties/fullName"
},
"relationship": {
"$id": "#/properties/traveller/items/properties/relationship",
"type": "string",
}
},
"required": [
"fullName",
"relationship"
],
}
}
}
}```
推荐答案
当前无法使用JSON模式完成.所有JSON Schema关键字一次只能操作一个值.有建议添加一个$data
关键字,以使您能够进行这种验证,但是我认为它不太可能被采用. $data
与$ref
一样,除了它引用正在验证的JSON而不是引用架构.
This can't currently be done with JSON Schema. All JSON Schema keywords can only operate on one value at a time. There's a proposal for adding a $data
keyword that would enable doing this kind of validation, but I don't think it's likely to be adopted. $data
would work like $ref
except it references the JSON being validated rather than referencing the schema.
这是使用$data
解决问题的方式.
Here's what how you would solve your problem with $data
.
{
"type": "object",
"properties": {
"policyHolder": {
"type": "object",
"properties": {
"fullName": { "type": "string" }
}
},
"traveler": {
"type": "array",
"items": {
"type": "object",
"properties": {
"fullName": { "type": "string" },
"relationship": { "type": "string" }
},
"if": {
"properties": {
"relationship": { "const": "My Self" }
}
},
"then": {
"properties": {
"fullName": { "const": { "$data": "#/policyHolder/fullName" } }
}
}
}
}
}
}
如果没有$data
,则必须在代码中进行此验证或更改数据结构,以使其不必要.
Without $data
, you will have to do this validation in code or change your data structure so that it isn't necessary.
这篇关于JSON模式if-else条件复杂场景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!