我想知道我是否可以定义一个JSON模式(草案4),该模式要求至少有一个属性具有特定值。
为了说明,这是一个我希望 FAIL 验证的JSON示例:
{
"daysOfWeek": {
"mon": false,
"tue": false,
"wed": false,
"thu": false,
"fri": false,
"sat": false,
"sun": false
}
}
但如果上述属性中的任何一个(一个或多个)设置为true
,那么我才会期望 PASS 验证。
那么Schema会是什么?
{
"daysOfWeek": {
"type": "object",
"properties": {
"mon": { "type": "boolean" },
"tue": { "type": "boolean" },
"wed": { "type": "boolean" },
"thu": { "type": "boolean" },
"fri": { "type": "boolean" },
"sat": { "type": "boolean" },
"sun": { "type": "boolean" }
},
"anyOf": [{
// ?
}]
}
}
非常感谢提前!
答案 0 :(得分:1)
您可以使用enum
关键字指定属性具有特定值。您可以将此技巧与anyOf
结合使用,以获得所需的验证行为。
{
"type": "object",
"properties": {
"daysOfWeek": {
"type": "object",
"properties": {
"mon": { "type": "boolean" },
"tue": { "type": "boolean" },
"wed": { "type": "boolean" },
"thu": { "type": "boolean" },
"fri": { "type": "boolean" },
"sat": { "type": "boolean" },
"sun": { "type": "boolean" }
},
"anyOf": [
{
"properties": {
"mon": { "enum": [true] }
}
},
{
"properties": {
"tue": { "enum": [true] }
}
},
{
"properties": {
"wed": { "enum": [true] }
}
},
{
"properties": {
"thu": { "enum": [true] }
}
},
{
"properties": {
"fri": { "enum": [true] }
}
},
{
"properties": {
"sat": { "enum": [true] }
}
},
{
"properties": {
"sun": { "enum": [true] }
}
}
]
}
}
}
答案 1 :(得分:1)
您可以将您的要求改为“不允许所有属性都为假”,在这种情况下,架构可以是:
{
"type": "object",
"properties": {...},
"not": {
"additionalProperties": {"enum": [false]}
}
}
additionalProperties
位于子架构中,因此它未连接到根级别的properties
值。因此,它适用于所有属性。
not
内的子模式只有在所有属性都为false
时才会通过 - 因此,只有当不所有属性都为false
时,外部模式才会通过。