如何在 json 模式中使用 `If` `then` `else` 条件?

How do I use the `If` `then` `else` condition in json schema?

JSON 架构(draft-07)的一个相对较新的添加项添加了 if、then 和 else 关键字。我不知道如何正确使用这些新关键词。到目前为止,这是我的 JSON 架构:

{
  "type": "object",
  "properties": {
    "foo": {
      "type": "string"
    },
    "bar": {
      "type": "string"
    }
  },
  "if": {
    "properties": {
      "foo": {
        "enum": [
          "bar"
        ]
      }
    }
  },
  "then": {
    "required": [
      "bar"
    ]
  }
}

如果"foo"属性等于"bar",那么"bar"属性是必需的。这按预期工作。

但是,如果 "foo" 属性 不存在或输入为空,那么我什么都不想要。如何实现?

empty input {}.

发现错误:
对象缺少必需的属性:栏。 架构路径:#/then/required

我使用在线验证工具:

https://www.jsonschemavalidator.net/

你不能只使用 "else" 属性 吗?

{
    "type": "object",
    "properties": {
        "foo": { "type": "string" },
        "bar": { "type": "string" }
     },
     "if": {
        "properties": {
            "foo": { 
              "enum": ["bar"] 
            }
        }
    },
    "then": { 
      "required": ["bar"]
    },
    "else": {
      "required": [] 
    }
}

if关键字表示,如果值模式的结果通过验证,则应用then模式,否则应用else模式。

您的架构无效,因为您需要在 if 架构中要求 "foo",否则空的 JSON 实例将通过 if 架构的验证,因此应用 then 架构,这需要 "bar".

其次,您需要 "propertyNames":false,这可以防止在模式中包含任何键,这与您设置 "else": false 不同,后者会使任何内容始终无法通过验证。

{
  "type": "object",
  "properties": {
    "foo": {
      "type": "string"
    },
    "bar": {
      "type": "string"
    }
  },
  "if": {
    "properties": {
      "foo": {
        "enum": [
          "bar"
        ]
      }
    },
    "required": [
      "foo"
    ]
  },
  "then": {
    "required": [
      "bar"
    ]
  },
  "else": false
}