我正在尝试根据以下输入进行 JSON 验证:
{
"elements":[
{
"..."
"isSelected": true
},
{
"..."
"isSelected": false
},
{
"..."
"isSelected": false
}
]
}
当且仅当我们将“isSelected”设置为“true”(其余所有设置为“false”)时,输入才有效。不能多次使用“isSelected: true”(其余所有都必须为“false”)。
尝试了以下内容:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"definitions": {
"element":{
"type": "object",
"properties": {
"isSelected": {
"type": "boolean"
}
}
}
},
"properties": {
"elements": {
"type": "array",
"items": {
"$ref": "#/definitions/element"
},
"oneOf": [
{
"isSelected": true
}
]
}
},
}
最佳答案
不幸的是,我认为 json 架构草案 7 不可能做到这一点。最新的草案 (2019-09) 具有 maxContains
关键字,它可以验证这一点,但为此需要工具到目前为止草稿很少。我不知道您正在使用的工具,但如果您能够使用 2019-09,“元素”的架构将类似于:
{
"type": "array",
"contains": {
"properties": {
"isSelected": {"const": true}
}
},
"maxContains": 1
}
oneOf 不是您要找的,为此 - 它检查一组模式中的一个是否针对实例进行验证,而不是一组实例中的一个是否针对模式进行验证。
关于jsonschema - 如何在数组中仅将一个属性值强制为 true(JSON 模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60961471/