Ron*_*Ron 5 validation jsonschema conditional-statements
根据这个问题jsonschema attribute conditionally required,我可以应用条件必需的属性。但是,它只能依赖于同一级别对象的属性。在某些情况下,我希望所需的一个属性依赖于其父对象属性,这可能吗?对于下面的例子:
{
type: 'object',
properties: {
{
os: { type: 'string', enum: ['macOs', 'windows'] },
specs: {
macModel: {
type: 'string',
enum: ['macbook air', 'macbook pro', 'macbook']
},
memory: { type: 'number' }
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以满足这个要求:仅当/os等于macOs时才需要/spec/macModel?
是的,同样的方法适用。您只需要将模式嵌套得更深一点即可。
{
"type": "object",
"properties": {
"os": { "enum": ["macOs", "windows"] },
"specs": {
"type": "object",
"properties": {
"macModel": { "enum": ["macbook air", "macbook pro", "macbook"] },
"memory": { "type": "number" }
}
}
},
"allOf": [{ "$ref": "#/definitions/os-macOs-requires-macModel" }],
"definitions": {
"os-macOs-requires-macModel": {
"anyOf": [
{ "not": { "$ref": "#/definitions/os-macOs" } },
{ "$ref": "#/definitions/requires-macModel" }
]
},
"os-macOs": {
"properties": {
"os": { "const": "macOs" }
},
"required": ["os"]
},
"requires-macModel": {
"properties": {
"specs": {
"required": ["macModel"]
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在/definitions/requires-macModel架构中,它必须深入研究“specs”属性并将其放置required在那里,而不是像在扁平情况下那样放置在顶层。
我在本示例中使用了蕴含模式,但也可以采用相同的方法if-then如果您更喜欢该方法并且可以访问 Draft-07 验证器。
| 归档时间: |
|
| 查看次数: |
2371 次 |
| 最近记录: |