如何在数组中强制只有一个 属性 值为真(JSON 模式)
How to enforce only one property value to true in an array (JSON Schema)
我正在尝试根据以下输入进行 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,'elements' 的架构将类似于:
{
"type": "array",
"contains": {
"properties": {
"isSelected": {"const": true}
}
},
"maxContains": 1
}
oneOf 不是您要找的,为此 - 它检查一组模式中的一个是否针对实例进行验证,而不是一组实例中的一个是否针对模式进行验证。
目前不支持此功能,但您可能对 this proposal 感兴趣,它打算添加关键字以支持基于键的项目唯一性。不完全一样,但我觉得是有关系的。
我正在尝试根据以下输入进行 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,'elements' 的架构将类似于:
{
"type": "array",
"contains": {
"properties": {
"isSelected": {"const": true}
}
},
"maxContains": 1
}
oneOf 不是您要找的,为此 - 它检查一组模式中的一个是否针对实例进行验证,而不是一组实例中的一个是否针对模式进行验证。
目前不支持此功能,但您可能对 this proposal 感兴趣,它打算添加关键字以支持基于键的项目唯一性。不完全一样,但我觉得是有关系的。