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

后端 未结 2 1452
孤独总比滥情好
孤独总比滥情好 2020-12-09 18:44

A relatively new addition to JSON Schema (draft-07) adds the if, then and else keywords. I cannot work out how to use these new key words correctly. Here is my JSON Schema s

相关标签:
2条回答
  • 2020-12-09 19:26

    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": [] 
        }
    }
    
    0 讨论(0)
  • 2020-12-09 19:41

    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
    }
    
    0 讨论(0)
提交回复
热议问题