Closed
Description
Here is an example:
import jsonschema
all_of = [
{"if": {"properties": {"enum_type": {"const": "TESTA"}}},
"then": {
"properties": {"enum_data": {"required": ["TESTA_FIELD1", "TESTA_FIELD2"], "additionalProperties": False}}
}},
{"if": {"properties": {"enum_type": {"const": "TESTB"}}},
"then": {
"properties": {"enum_data": {"required": ["TESTB_FIELD1", "TESTB_FIELD2"], "additionalProperties": False}}
}},
]
top_level = {
"type": "object",
"properties": {
"enum_type": {
"type": "string",
"enum": ["TESTA", "TESTB"],
},
},
"required": ["enum_type", "enum_data"],
"allOf": all_of,
}
data = {
"enum_type": "TESTA",
"enum_data": {"TESTA_FIELD1": "value"}
}
data2 = {
"enum_type": "TESTA",
"enum_data": {"TESTA_FIELD1": "value", "TESTA_FIELD2": "value"}
}
data3 = {
"enum_type": "TESTA",
"enum_data": {"TESTA_FIELD1": "value", "TESTA_FIELD2": "value", "UNWANTED_FIELD": "value"}
}
for d in [data, data2, data3]:
try:
jsonschema.validate(instance=d, schema=top_level)
except jsonschema.ValidationError as ve:
key = '__root__.' + '.'.join(ve.path)
msg = f"Key <{key}>: {ve.message}"
print(msg)
Output:
Key <__root__.enum_data>: 'TESTA_FIELD2' is a required property
Key <__root__.enum_data>: Additional properties are not allowed ('TESTA_FIELD1', 'TESTA_FIELD2' were unexpected)
Key <__root__.enum_data>: Additional properties are not allowed ('TESTA_FIELD1', 'UNWANTED_FIELD', 'TESTA_FIELD2' were unexpected)
First validation is expected because TESTA_FIELD2
is required.
Second validation is wrong. It should pass without errors.
Third validation should fail but with only UNWANTED_FIELD
as unexpected.
Metadata
Metadata
Assignees
Labels
No labels