根据这个问题 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' }
}
}
}
}
是否可以满足这个要求:/spec/macModel 仅当 时才需要/os 等于 macOS ?
最佳答案
是的,同样的方法也适用。您只需要将模式嵌套得更深一些。
{
"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"]
}
}
}
}
}
请注意,在 /definitions/requires-macModel
中架构它必须深入研究“规范”属性并放置 required
在那里而不是在平面情况下的顶层。我在这个例子中使用了蕴涵模式,但同样的方法可以用于
if
- then
如果您更喜欢这种方法并且可以访问draft-07验证器。
关于validation - 有条件地需要 jsonSchema 属性取决于父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51203606/