I have multiple schemas, each one for data sub-type:
type_one = {
"type": "object",
"properties": {
"one": "string"
}
}
type_two = {
"type": "object",
"properties": {
"one": "string",
"two": "string"
}
}
What I want is to check if incoming data is "type_one" OR "type_two" or throw an error. Something like this:
general_type = {
"type": [type_one, type_two]
}
My incomming data is like this:
{
"one": "blablabla",
"two": "blebleble",
...
}
I have been testing several ways but no success... any ideas? Thx
You can use the property "additionalProperties": False
in your object schema to only allow an exact set of keys.
First, let's have valid schema structures:
type_one = {
"type": "object",
"additionalProperties": False,
"properties": {
"one": {"type": "string"}
}
}
type_two = {
"type": "object",
"additionalProperties": False,
"properties": {
"one": {"type": "string"},
"two": {"type": "string"}
}
}
general_type = {
"type": [type_one, type_two]
}
NOTE: the schema from your question is "one": "string"
, it should be "one": {"type": "string"}
Here is our input data:
data_one = {
"one": "blablabla"
}
data_two = {
"one": "blablabla",
"two": "blablabla"
}
And here is the validation:
import validictory
# additional property 'two' not defined by 'properties' are not allowed
validictory.validate(data_two, type_one)
# Required field 'two' is missing
validictory.validate(data_one, type_two)
# All valid
validictory.validate(data_one, type_one)
validictory.validate(data_two, type_two)
validictory.validate(data_one, general_type)
validictory.validate(data_two, general_type)
I hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.