Reputation: 101
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"description": "My sample Json",
"type": "object",
"properties": {
"eventId": {
"description": "The event Indetifier",
"type": [ "number", "string" ]
},
"serviceType": {
"description": "The service type. It can be either ABC or EFG",
"enum": [ "ABC", "EFG" ]
},
"parameters": { "$ref": "/schemas/parameters" }
},
"required": [ "eventId", "serviceType" ],
"$defs": {
"parameters": {
"$id": "/schemas/parameters",
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Other Parameters",
"type": "object",
"properties": {
"activityType": {
"description": "The activity type",
"type": [ "null", "string" ]
},
"activitySubType": {
"description": "The activity sub type",
"type": [ "null", "string" ]
}
}
}
}
}
Now I have requirement to perform some validation logic.
I am trying to perform the validation using "if then else" condition. I am not sure how to add that inside the Json Schema validator.
Can anyone help me with the syntax? Is it possible to do that?
Upvotes: 0
Views: 1044
Reputation: 53986
This is definitely possible. For the first requirement:
{
...
"if": {
"required": [ "eventId", "serviceType" ],
"properties": {
"eventId": {
"const": "100"
},
"serviceType": {
"const": "ABC"
}
}
},
"then": {
"required": [ "parameters" ],
"properties": {
"parameters": {
"properties": {
"activityType": {
"type": "string",
"minLength": 10
}
}
}
},
...
}
The "required" keywords are there because if the property doesn't exist at all, the "if" subschema will validate as true, which you don't want -- you need to say "if this property exists, and its value is ..., then ...".
The second requirement is very similar to the first. You can use multiple "if"/"else" keywords in the schema at the same time by wrapping them in an allOf: "allOf": [ { ..schema 1..}, { ..schema 2.. } ]
Upvotes: 2