It involves applying validation rules based on presence or absence of other properties in a JSON schema.

Example

  • dependentRequired: if property A is present, then property B is required
  • dependentSchemas: if a property A is present, then apply subschema
  • if-then-else: if a subschema A is valid, then subschema B must be valid, else subschema C must be valid
  • implications: if subschema A is valid then subschema B must be valid

Require dependency

You can use dependentRequired property to conditionally make a property required based on presence of another one

{  
	"type": "object",  
	"properties": {  
		"name": {  
			"type": "string"  
		},  
		cc: {  
			"type": "string'  
		},  
		"address": {  
			"type": "string"  
		}  
	},  
	"required": ['name'],  
	"dependentRequired": {  
		"cc": "address"  
	}  
}  

Mutual dependency

Sometimes you will have to validate the presence of both properties if at least one of them exists. For example, iffirstName or lastName are present, then both should be required. To enable that, you can use dependentSchema keyword

{  
	"type": "object",  
	"properties": {  
		"firstName": {  
			"type": "string"  
		},  
		"lastName": {  
			"type": "string"  
		}  
	},  
	"dependentRequired": {  
		"firstName": ["lastName"],  
		"lastName": ["firstName"]  
	}  
}  

Conditional Subschema

You can apply subschema based on the presence or absence of another property. For that, you can use dependentSchema keyword.

{  
  "type": "object",  
  "properties": {  
    "name": {  
      "type": "string"  
    },  
    "creditCardNumber": {  
      "type": "string"  
    }  
  },  
  "dependentSchemas": {  
    "creditCardNumber": {  
      "properties": {  
        "address": {  
          "type": "string"  
        }  
      },  
      "required": [  
        "address"  
      ]  
    }  
  },  
  "required": [  
    "name"  
  ]  
}  

Implications

You can do if-then statements in JSON Schema when you want to enable property based on, for example, value of another property

{  
	"type": "object",  
	"properties": {  
		"name": {  
			"type": "string"  
		},  
		"age": {  
			"type": "integer"  
		},  
		"isStudent": {  
			"type": "boolean"  
		},  
		"if": {"properties": {"isStudent": {"const": true}}, "required": ["isStudent"]},  
		"then": {"required": ["age"]}  
	}  
}  

If-then-else

If you want to apply subschema conditionally when condition is true or false, you can use if-then-else. When using this, you need to make sure that the value you use for conditional check is required.

{  
	"type": "object",  
	"properties": {  
		"name": {  
			"type": "string"  
		},  
		"isFullTime": {  
			"type": "boolean"  
		},  
		"salary": {  
			"type": "number"  
		},  
		"hourlyRate": {  
			"type": "number"  
		},  
		"if": {"properties": {"isFullTime": {"const": true}}},  
		"then": {"required": ["salary"]},  
		"else": {"required": ["hourlyRate"]}  
	}  
}