有条件需要的jsonSchema属性取决于父对象 [英] jsonSchema attribute conditionally required depends on parent object

查看:132
本文介绍了有条件需要的jsonSchema属性取决于父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Per this question jsonschema attribute conditionally required, I can apply conditional required properties. However, it can only depend on the properties on the same level of object. In certain case, I want to one property required depend on its parent object property, is it possible? For the below example:

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

是否有可能满足此要求:<仅当 / os 等于 macOs 时才需要strong> / spec / macModel ?

Is it possible to meet this requirement: /spec/macModel is required only when /os equals to macOs?

推荐答案

是的,适用相同的方法。您只需要将模式嵌套得更深。

Yes, the same approach applies. You just need to nest schemas a little deeper.

{
  "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 架构中必须深入研究规范属性,然后将必需的放置在此处,而不是放在平坦情况下的顶层。

Notice that in the /definitions/requires-macModel schema it has to dig into the "specs" property and place the required there instead of at the top level as it is in the flat case.

我已经使用了蕴涵此示例的模式,但是如果您喜欢该方法并且可以访问,则可以使用--然后使用相同的方法到草案07验证者。

I've used the implication pattern for this example, but the same approach can be taken with if-then if you prefer that approach and have access to a draft-07 validator.

这篇关于有条件需要的jsonSchema属性取决于父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆