【问题标题】:Metaschema specifying required attribute for all properties为所有属性指定所需属性的元模式
【发布时间】:2018-07-03 18:17:36
【问题描述】:

我想自定义一个元模式,使得所有属性都需要有一个附加属性,例如,我怎么能要求所有属性都指定一个"type"

那么这个架构应该会失败:

{
    "$schema": "http://json-schema.org/schema#",
    "title": "...",
    "description": "...",
    "type": "object",
    "properties": {
        "name": {
            "description": "..."
        }
    }
}

但这一次应该会成功:

{
    "$schema": "http://json-schema.org/schema#",
    "title": "...",
    "description": "...",
    "type": "object",
    "properties": {
        "name": {
            "description": "...",
            "type": "string"
        }
    }
}

【问题讨论】:

  • 这会解决什么问题?

标签: json jsonschema


【解决方案1】:

不幸的是,编写元模式并不容易。正在研究中,但还没有好的解决方案。

您必须复制要扩展的元模式,然后添加"required": ["type"]

但是,当我们在这里时,也许我可以说服你不要这样做。在某些情况下,将 type 关键字设为必需会导致问题。这里有一些例子。 https://github.com/json-schema/json-schema/issues/172#issuecomment-124214534

编辑

在进一步讨论后,我们发现这种特殊情况没有我们通常在扩展元模式时遇到的问题,因为它不需要递归。下面是扩展 Draft-06 架构以包含名为 custom 的新关键字的示例,它是一个布尔值,仅在 properties 架构的顶层需要。

{
  "allOf": [
    { "$ref": "http://json-schema.org/draft-06/schema#" },
    {
      "properties": {
        "properties": {
          "patternProperties": {
            ".*": {
              "properties": {
                "custom": { "type": "boolean" }
              },
              "required": ["custom"]
            }
          }
        }
      }
    }
  ]
}

这是一个符合此元模式的示例模式。

{
  "properties": {
    "foo": {
      "custom": true,
      "not": { "type": "string" }
    }
  }
}

“foo”架构需要 custom 关键字,而不是 not 架构或顶级架构。

【讨论】:

  • 谢谢@Jason,我的印象是我可以使用allOf 来包含来自普通draft-X 模式的所有条件,然后添加一个新要求。我知道有理由不需要type,在我们的情况下我们可能不需要它,但是我们确实肯定需要一个自定义属性是所有属性所必需的,我只是以type 为例。
  • 不幸的是,这并不容易。这有点难以解释(尤其是在评论中),但是当您只使用allOf 时,只有架构的顶层会包含新的约束。任何其他模式,例如 properties 中的模式都不会改变。
  • 感谢您的解释 - 他们非常有帮助!但是,哎呀。这太残酷了……对于许多用例来说,这似乎很大程度上是一个交易破坏者。
  • 此架构不暗示 type 检查。参数custom 可以是任何类型。要同时控制类型,您需要将custom 作为属性包含在patternProperties 中,例如:{"allOf": [{"$ref": "http://json-schema.org/draft-06/schema#"},{"properties": {"properties": {"patternProperties": { "^.*$": { "properties": { "custom": { "type": "boolean" } }, "required": [ "custom" ] } } } } } ] }
  • @ollamh 感谢您指出这一点。我已经修好了。它当然会检查类型,只是在错误的级别上检查。
猜你喜欢
  • 1970-01-01
  • 2018-05-24
  • 2010-11-14
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
  • 2015-10-03
相关资源
最近更新 更多