【问题标题】:How do I use the `If` `then` `else` condition in json schema?如何在 json 模式中使用 `If` `then` `else` 条件?
【发布时间】:2018-07-26 13:05:44
【问题描述】:

对 JSON Schema (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 {}.

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

我使用在线验证工具:

https://www.jsonschemavalidator.net/

【问题讨论】:

  • 您可能觉得格式不重要,但它可以帮助人们回答您的问题。链接的在线验证器甚至有一个按钮可以为您自动格式化 JSON。请使用它。
  • “我什么都不想要”这句话没有任何意义。你能改写一下吗?我假设您的意思是“我不希望对象中有任何值”。对吗?

标签: jsonschema


【解决方案1】:

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
}

【讨论】:

    【解决方案2】:

    你不能只使用“else”属性吗?

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

    【讨论】:

    • 如果键 foo 不包含在 JSON 实例中,这将不起作用。
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2019-04-25
    相关资源
    最近更新 更多