Conditionally Apply a Subschema

When you want to apply a subschema based on the presence or absence of a property, you can use the dependentSchemas keyword. This keyword allows you to define a subschema that is applied only when a specific property is present or absent.

Example

Let's say, our employee document has a property address. If address is present, then contact must include a phone number and email address.

1{
2  "name": "John Doe",
3  "address": "123 Main St",
4  "contact": {
5    "phone": "123-456-7890",
6    "email": "[email protected]"
7  }
8}

You can use the dependentSchemas keyword to enforce this condition.

Example Schema

1{
2  "type": "object",
3  "properties": {
4    "address": {"type": "string"},
5  },
6  "dependentSchemas": {
7    "address": {
8      "properties": {
9        "contact": {
10          "type": "object",
11          "properties": {
12            "phone": {"type": "string"},
13            "email": {"type": "string"}
14          },
15          "required": ["phone", "email"]
16        }
17      }
18    }    
19  }
20}

Task

1{
2  "name": "John Doe",
3  "creditCardNumber":"1234 5678 1234 5678",
4  "address":"123 Main St"
5}

You are given a Schema for the above JSON document in the side editor. Update the schema to make sure that if the creditCardNumber property is present, then the address property must also be present using the dependentSchemas keyword.

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