So I am working on this problem where I have to validate the json schema based on some conditions. If xy-ac is in the schema then I want source to be present there as well. It is required. Currenlty, I am doing this in code by checking if source not in the json payload then throw an exception. I want that validation to be done at json validation schema level.
SOME_SCHEMA = {
"$schema": "http://json-schema.org/draft-07/schema#",
"required": ["a", "b", "c", "datasetInfo", "d"],
"properties": {
"source": {"$ref": "#/definitions/source"},
},
"additionalProperties": False,
"definitions": {
...
"subscriptionID": {"type": "string",
"pattern": "^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$"},
"source": {
"type": "object",
"required": ["subscriptionIDs"],
"properties": {
"subscriptionIDs": {
"type": "array",
"items": {"$ref": "#/definitions/subscriptionID"},
"minItems": 1
}
},
"additionalProperties": False
},
"datasetInfo": {
"type": "object",
"properties": {
"xyz-ad": {
"type": "object"
},
"xy-ac": {
"type": "object"
}
},
"additionalProperties": False,
"minProperties": 1,
}
}
}
I have tried a couple of options but am not able to get it to work.
Attempt 1:
"dependencies": {
"xy-ac": [{"$ref": "#/definitions/source"}]
}
Attempt 2:
SOME_SCHEMA = {
"$schema": "http://json-schema.org/draft-07/schema#",
"required": ["a", "b", "c", "datasetInfo", "d"],
"properties": {
"source": {"$ref": "#/definitions/source"},
},
"additionalProperties": False,
"definitions": {
...
"subscriptionID": {"type": "string",
"pattern": "^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$"},
"source": {
"type": "object",
"required": ["subscriptionIDs"],
"properties": {
"subscriptionIDs": {
"type": "array",
"items": {"$ref": "#/definitions/subscriptionID"},
"minItems": 1
}
},
"additionalProperties": False
},
"datasetInfo": {
"type": "object",
"properties": {
"xyz-ad": {
"type": "object"
},
"xy-ac": {
"type": "object"
"required": ["source"],
"properties": {
"source": {"$ref": "#/definitions/source"}
}
}
},
"additionalProperties": False,
"minProperties": 1,
}
}
}
None of the above approaches worked. I can provide more info if my question is not clear. Appreciate any pointers
Looks like you have a few problems here. Not uncommon, so don't worry.
You tried to use
dependentSchemaswithdraft-07JSON Schema.Official docs: https://json-schema.org/understanding-json-schema/reference/conditionals.html#dependentrequired
... "required": {"$ref": "#/definitions/source"}The
requiredkeyword takes an array of strings. Most validators would pick up your schema section as an error.I can't really tell what your second attempt entales. It's best if you provide the FULL Schema.
You might find the docs on conditional validation helpful, specifically how to use
if/then/else: https://json-schema.org/understanding-json-schema/reference/conditionals.html#if-then-else