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

jsonSchema attribute conditionally required depends on parent object

根据这个问题 ,我可以应用有条件的必需属性。但是,它只能依赖于同一级别对象上的属性。在某些情况下,我想要一个 属性 依赖于它的父对象 属性,它是 possible 吗?对于以下示例:

{
  type: 'object',
  properties: {
    { 
      os: { type: 'string', enum: ['macOs', 'windows'] },
      specs: {
        macModel: { 
          type: 'string', 
          enum: ['macbook air', 'macbook pro', 'macbook']
        },
        memory: { type: 'number' }
      }
    }
  }
}

是否pos可以满足这个要求:/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 放在那里,而不是像在平面中那样放在顶层案例.

我在此示例中使用了蕴含模式,但如果您更喜欢这种方法并且可以访问 draft-07 验证器,则可以对 if-then 采用相同的方法。