问题
I want to validate sale date and customer availability based on the value of ordertype.(Note., They are not under same object).Is there any way to validate child values based on root value?
{
"type": "object",
"properties": {
"Order": {
"type": "object",
"properties": {
"OrderDetails": {
"type": "object",
"properties": {
"OrderType": {
"type": "string",
"enum": [
"Y",
"N"
]
}
}
}
}
},
"Sale": {
"type": "object",
"properties": {
"Saledate": {
"format": "date"/*should be present when OrderType is Y*/
}
}
},
"Customer": {
"type": "object",
"properties": {
"Avilability": {
"type": "string",
"enum": [
"Y",
"N"
]/*should be present when orderType is Y*/
}
}
}
}
}
回答1:
You can use if
/then
to create describe the constraint. The trick is that you need to add the constraint at a high enough level in the schema that it covers all of the properties involved.
{
...
"if": {
"type": "object",
"properties": {
"Order": {
"type": "object",
"properties": {
"OrderDetails": {
"type": "object",
"properties": {
"OrderType": { "const": "Y" }
},
"required": ["OrderType"]
}
},
"required": ["OrderDetails"]
}
},
"required": ["Order"]
},
"then": {
"properties": {
"Sale": { "required": ["Saledate"] },
"Customer": { "required": ["Availability"] }
},
"required": ["Sale", "Customer"]
}
}
来源:https://stackoverflow.com/questions/64258202/how-to-validate-a-object-based-on-the-value-of-root-object-in-json-schema