如何检查以下JSON中的属性isCorrect
是否仅具有一次值true
。将其视为只有一个答案的多项选择题,因此数组中可以有很多元素,但答案在所有元素中只能是一次。
"answers": [
{
"id": 1,
"text": "choice1",
"isCorrect": true
},
{
"id": 1,
"text": "choice2",
"isCorrect": true
},
{
"id": 1,
"text": "choice3",
"isCorrect": false
},
{
"id": 1,
"text": "choice4",
"isCorrect": false
}
]
}
我使用contains
来验证至少一个元素是否满足条件,但是即使isCorrect
为true
的元素多于1个,它也会进行验证,因此我使用了maxContains
,但它不满足工作。
我的模式:
{
"definitions": {},
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://eg.com/schema2.json",
"type": "object",
"title": "Example",
"required": ["answers"],
"properties": {
"answers": {
"type": "array",
"contains": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"text": {
"type": "string"
},
"isCorrect": {
"type": "boolean",
"enum": [true]
}
}
},
"maxContains": 1,
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"text": {
"type": "string"
},
"isCorrect": {
"type": "boolean"
}
}
}
}
}
}
此实例不应该被验证,因为它的true
值对于isCorrect
出现了两次,并且架构将maxContains
提到为1,但是它不起作用。我在做什么错,maxContains
的位置是否错误?任何帮助表示赞赏!
minContains
中添加maxContains
和draft 2019-09
。它们不是draft-07
的一部分,未知关键字将被忽略。
在撰写本文时,2019-09年草案很新,只有一个已知的实现。
目前,您必须自己将关键字实现为扩展(如果您使用的库支持此类功能,或者编写在JSON模式验证之后发生的其他业务逻辑代码。