我想在json模式中完成的:当属性enabled
true
时,应该需要某些其他属性。false
时,应禁止这些属性。
这是我的 json 模式:
{
"type": "object",
"properties": {
"enabled": { "type": "boolean" }
},
"required" : ["enabled"],
"additionalProperties" : false,
"if": {
"properties": {
"enabled": true
}
},
"then": {
"properties": {
"description" : { "type" : "string" },
"count": { "type": "number" }
},
"required" : ["description", "count"]
}
}
使用ajv
版本 6.5 进行验证,这会导致需要count
等,而不管enabled
的值如何。例如,对于数据:
{ "enabled": false }
我的验证错误是:
[ { keyword: 'required',
dataPath: '',
schemaPath: '#/then/required',
params: { missingProperty: 'description' },
message: 'should have required property 'description'' },
{ keyword: 'required',
dataPath: '',
schemaPath: '#/then/required',
params: { missingProperty: 'count' },
message: 'should have required property 'count'' },
{ keyword: 'if',
dataPath: '',
schemaPath: '#/if',
params: { failingKeyword: 'then' },
message: 'should match "then" schema' } ]
如何使用 json 架构draft-7
完成此操作?
请注意,此问题与以下问题类似,但要求比以下
条件要求的 jsonSchema 属性更严格。
试试这个架构:
{
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
}
},
"required": [
"enabled"
],
"if": {
"properties": {
"enabled": {
"const": true
}
}
},
"then": {
"properties": {
"enabled": {
"type": "boolean"
},
"description": {
"type": "string"
},
"count": {
"type": "number"
},
"additionalProperties": false
},
"required": [
"description",
"count"
]
},
"else": {
"properties": {
"enabled": {
"type": "boolean"
}
},
"additionalProperties": false
}
}
如果需要"additionalProperties": false
则必须枚举then
和else
中的所有属性。如果可以接受其他属性,则架构可能会更简单:
{
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
}
},
"required": [
"enabled"
],
"if": {
"properties": {
"enabled": {
"const": true
}
}
},
"then": {
"properties": {
"description": {
"type": "string"
},
"count": {
"type": "number"
}
},
"required": [
"description",
"count"
]
}
}
我检查了ajv
cli。
有效:{"enabled": false}
无效:{"enabled": true}
有效:{"enabled": true, "description":"hi", "count":1}
这是受到vearutop的出色回答的启发。我认为它可能会短一点,并达到我所说的目的。
{
"type": "object",
"oneOf" : [
{
"properties": {
"enabled": { "const": false }
},
"required": ["enabled"],
"additionalProperties": false
},
{
"properties": {
"enabled": { "const": true },
"description": { "type": "string" },
"count": { "type": "number" }
},
"required": [ "enabled", "description", "count"],
"additionalProperties": false
}
]
}
正如评论中指出的那样,这是本答案中阐述的Enum策略的特定变体。
为此,在if
语句中,您需要使用const
关键字,因此架构如下所示:
{
"type": "object",
"properties": {
"enabled": { "type": "boolean" }
},
"required" : ["enabled"],
"additionalProperties" : false,
"if": {
"properties": {
"enabled": {"const": true}
}
},
"then": {
"properties": {
"description" : { "type" : "string" },
"count": { "type": "number" }
},
"required" : ["description", "count"]
}
}