我试图在 json-schema 中完成的是:当属性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"]
}
}
Run Code Online (Sandbox Code Playgroud)
使用ajv6.5 版进行验证count,无论 的值如何,这都会导致 require等enabled。例如,对于数据:
{ "enabled": false }
Run Code Online (Sandbox Code Playgroud)
我的验证错误是:
[ { 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' } ]
Run Code Online (Sandbox Code Playgroud)
如何使用 json-schema 完成此操作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
}
}
Run Code Online (Sandbox Code Playgroud)
如果你需要"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"
]
}
}
Run Code Online (Sandbox Code Playgroud)
我检查了ajvcli。
有效的: {"enabled": false}
无效的: {"enabled": true}
有效的: {"enabled": true, "description":"hi", "count":1}