有条件地验证json模式中的一个Array对象



只有当类型mobile并且endDate是空/null时,下面的json才有效,否则验证需要失败。这里类型可以有任何值,但我的验证仅适用于移动类型。

有效json:

{
"contacts": [
{
"type": "mobile",
"endDate": "",
"number": "1122334455"
},
{
"type": "home",
"endDate": "",
"number": "1111122222"
},
{
"type": "mobile",
"endDate": "12-Jan-2017",
"number": "1234567890"
},
]
}

无效json:(因为联系人没有有效的手机号码(

{
"contacts": [
{
"type": "mobile",
"endDate": "12-Jan-2021",
"number": "1122334455"
},
{
"type": "home",
"endDate": "",
"number": "1111122222"
},
{
"type": "mobile",
"endDate": "12-Jan-2017",
"number": "1234567890"
},
]
}

我尝试的架构

{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"type": "object",
"properties": {
"contacts": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"endDate": {
"type": [
"string",
"null"
]
},
"number": {
"type": "string"
}
},
"anyOf": [
{
"if": {
"properties": {
"type": {
"const": "mobile"
}
}
},
"then": {
"properties": {
"endDate": {
"maxLength": 0
}
}
}
}
]
}
}
}
}

有人能为我提供一个正确的json模式吗?在这里附上示例代码,这是有效的json,但会出错。这里是无效的json示例,原因是类型mobile没有空的endDate。提前谢谢。

我找到了一些答案,我们不需要使用anyOfoneOf。正确的是contains。CCD_ 4的位置也是一个重要因素。工作示例是

这是正确的模式

{
"type": "object",
"properties": {
"contacts": {
"type": "array",
"minItems": 1,
"contains": {
"type": "object",
"properties": {
"type": {
"const": "mobile"
},
"endDate": {
"type" : ["string", "null"],
"maxLength": 0
}
},
"required": ["type"]
},
"items": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"endDate": {
"type": [
"string",
"null"
]
},
"number": {
"type": "string"
}
}
}
}
}
}

您的模式定义properties > data,但实例数据使用contacts而不是data。更改任一项都可以解决您的问题。否则,您的操作是正确的。

(如果您只有一个type要检查,则不需要将if/then模式包装在anyOf中。(

最新更新