validation - 有条件地需要 jsonSchema 属性取决于父对象

标签 validation conditional jsonschema

根据这个问题 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/

相关文章:

php - Laravel 验证 : validate field only if another is present

javascript - 如何使用有效的标记维护动态页面标题?

C# 清理文件名

jquery - 使用 parsley.js 验证单选按钮

PHP条件逻辑,具体顺序?

使用条件关键字的 JSON Schema 交叉键约束支持

javascript - 检查 JavaScript 函数是否在不执行的情况下返回?

xslt - 如何在 XSLT 选择中执行 'and' 语句?

python - 如何使用 GraphQL 模式进行类似 JSON 模式的数据验证?

java - 不会生成数组 List<ComplexType> 而是 List<Object>