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

筅森魡賤 提交于 2019-11-29 07:12:43

The if keyword means that, if the result of the value schema passes validation, apply the then schema, otherwise apply the else schema.

Your schema didn't work because you needed to require "foo" in your if schema, otherwise an empty JSON instance would pass validation of the if schema, and therefore apply the then schema, which requires "bar".

Second, you want "propertyNames":false, which prevents having any keys in the schema, unlike if you were to set "else": false which would make anything always fail validation.

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

Can't you just use the "else" property ?

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

What if these keys are not on same level e.g. C1 is Required when A1.B1 is V1 i.e.

{ "A1":{ "B1":"V1" } }

So C1 should only be required when A1 and B1 both exists and A1.B1 is V1.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!