JSON Schema (draft-07)的一个相对较新的添加添加了if、then和else关键字。我不知道如何正确地使用这些新的关键词。以下是我到目前为止的JSON Schema:
{
  "type": "object",
  "properties": {
    "foo": {
      "type": "string"
    },
    "bar": {
      "type": "string"
    }
  },
  "if": {
    "properties": {
      "foo": {
        "enum": [
          "bar"
        ]
      }
    }
  },
  "then": {
    "required": [
      "bar"
    ]
  }
}如果"foo“属性等于"bar",则"bar”属性是必需的。这与预期的一样。
但是,如果"foo“属性不存在或者输入为空,那么我什么都不想要。如何做到这一点呢?
empty input {}.发现错误:
     Required properties are missing from object: bar.     Schema path: #/then/required我使用在线验证工具:
发布于 2018-07-26 21:22:57
if关键字表示,如果值模式的结果通过验证,则应用then模式,否则应用else模式。
您的模式不起作用,因为您需要在if模式中使用"foo",否则一个空的JSON实例将通过if模式的验证,从而应用需要"bar"的then模式。
其次,您需要"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
}发布于 2018-07-26 21:19:34
不能只使用"else“属性吗?
{
    "type": "object",
    "properties": {
        "foo": { "type": "string" },
        "bar": { "type": "string" }
     },
     "if": {
        "properties": {
            "foo": { 
              "enum": ["bar"] 
            }
        }
    },
    "then": { 
      "required": ["bar"]
    },
    "else": {
      "required": [] 
    }
}https://stackoverflow.com/questions/51539586
复制相似问题