14
votes

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 so far:

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

If the "foo" property equals "bar", Then the "bar" property is required. This works as expected.

However, if the "foo" property does not exist or input is empty then I don't want anything. how to acheive this?

empty input {}.

Found Errors:
Required properties are missing from object: bar. Schema path: #/then/required

I use online validation tool:

https://www.jsonschemavalidator.net/

2
You may not feel that formatting is important, but it helps people answer your question. The linked online validator even has a button to auto format your JSON for you. Please use it.Relequestual
The phrase "I dont want anything" doesn't make any sense. Can you rephrase this? I've assumed you mean, "I do not want any values in the object". Is that correct?Relequestual

2 Answers

16
votes

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
votes

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": [] 
    }
}