Expanding If-Then-Else

So far, you've learned how to use if-then-else for conditionals. This lesson will show how they can be combined with different validation rules, not just constants!

Using with not Keyword

The not keyword allows you to negate a condition (or any schema rule), meaning a property must not match a specified type or constraint. For example, the following schema ensures that the name property can be anything except a string:

1{
2  "type": "object",
3  "properties": {
4   "name": {
5      "type": {"not": {"type": "string"}}
6    } 
7  }
8}

Using the not keyword with the if-else keyword can look something like this:

Example Schema

1{
2  "type": "object",
3  "properties": {
4    "status": { 
5      "type": "string", 
6      "enum": ["employed", "unemployed"] 
7      },
8    "salary": { 
9      "type": "number" 
10      },
11    "unemploymentBenefits": { 
12      "type": "number" 
13      }
14  },
15  "if": { 
16    "properties": {
17       "status": { "const": "employed" } 
18    } 
19  },
20  "then": { 
21    "not": { "required": ["unemploymentBenefits"] 
22    } 
23  }
24}
  • If status is "employed", the unemploymentBenefits field must not be present.
  • If status is "unemployed", unemploymentBenefits field can be present.

This demonstrates that conditionals in JSON Schema can be combined with various keywords, allowing for more flexible validation rules.

Task

1{
2    "name": "John Doe",
3    "age": 20,
4    "grade": 8,
5    "recommendationLetter": "Dr. Smith's letter",   
6}

You are given the schema for the same JSON document in the side editor. Modify the schema to enforce the below condition using if-then-else:

  • If grade is greater that or equal to 8, then the recommendationLetter field must be present, and the personalStatement field must NOT be present.
  • Else if grade is lower than 8, then the personalStatement field must be present, and the recommendationLetter field must NOT be present..

Hint: Use the minimum keyword to specify the constraint of greater than or equal to 8.

Loading...
Output
Please click the button or use
Shift+Enter
to view the output