I can't seem to figure out how conditional validation works. I'm trying to use the if-else statement to validate a section but I've been unable to figure out whether or not I'm doing it correctly. Here is my validation JSON:
{
"$schema": "summaryAttributes#",
"$id": "summaryAttributes",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"processing": {
"type": "object",
"properties": {
"full": { "type": "string" }
}
,
"required": [ "full" ]
},
"if": {
"properties": {
"name": "summary"
}
},
"then": {
"properties": {
"analysis": {
"type": 'object',
"properties": {
"summary": { "type": "string" }
},
"required": [ "summary" ]
}
}
},
"else": {
"properties": {
"analysis": {
"type": 'object',
"properties": {
"fileDescription": { "type": "string" }
},
"required": [ "fileDescription" ]
}
}
},
"additionalProperties": false,
"required": [ "name", "processing", "analysis" ]
}
}
Here is some data that I would expect NOT to validate, but it does.
{
name: "summary",
processing: {
full: "Some random text",
},
analysis: {
summary: "",
}
}
Here's a more comprehensive schema that satisfies your conditional statement.
It has a valid JSON Schema $schema
value and it uses the conditional statement as a sibling to the properties
keyword, which is where it must be defined. Because you are using additionalProperties: false
the analysis
keyword must be defined at the root with an empty schema (or boolean true schema) to allow the validator to recognize this keyword.
It's good practice to include the conditional statements in an allOf
to allow for future expansion of more conditional statements.
I also used the definitions
keyword to provide an easier definition name to reference the individual conditional statements.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "summaryAttributes",
"type": "object",
"properties": {
"name": {"type": "string"},
"processing": {
"type": "object",
"properties": {
"full": {"type": "string"}
},
"required": ["full"]
},
"analysis": {} // or "analysis": true works just as well
},
"allOf": [
{"$ref": "#/definitions/SummaryAnalysisOrFileDescription"}
],
"definitions": {
"SummaryAnalysisOrFileDescription": {
"if": {
"required": ["name"],
"properties": {
"name": {"const": "summary"}
}
},
"then": {
"required": ["analysis"],
"properties": {
"analysis": {
"type": "object",
"additionalProperties": false,
"properties": {
"summary": {"type": "string"}
},
"required": ["summary"]
}
}
},
"else": {
"required": ["analysis"],
"properties": {
"analysis": {
"type": "object",
"additionalProperties": false,
"properties": {
"fileDescription": {"type": "string"}
},
"required": ["fileDescription"]
}
}
}
}
},
"additionalProperties": false,
"required": ["name", "processing", "analysis"]
}
the example you provided successfully validates this schema, as it should based on the way you wrote your schema