Reputation: 65
I need to validate json
[
{
"relatedParty": "tr13",
"action": "b"
},
{
"relatedParty": "er127"
}
]
I would like to validate stricture and properties values. So I've written the following json schema:
{
"type": "array",
"maxItems": 4,
"items": {
"type": "object",
"oneOf": [
{
"properties": {
"relatedParty": {
"type": "string",
"pattern": "tr\\d{2}"
},
"action": {
"type": "string",
"pattern": "a"
}
}
},
{
"properties": {
"relatedParty": {
"type": "string",
"pattern": "er\\d{3}"
}
}
}
]
}
}
But if I have wrong value in action I get validation message for both relatedParty and action properties.
Could anyone one explain why I got 2 validation messages rather then one and how it possible to adjust my validation schema to get only 1 message?
UPDATES:
Tried to validate the same json-object with the following json-schema:
{
"type": "array",
"maxItems": 4,
"items": {
"type": "object",
"properties": {
"relatedParty": {
"type": "string",
"oneOf": [
{
"pattern": "tr\\d{2}"
},
{
"pattern": "er\\d{3}"
}
]
}
},
"$defs": {
"tr-requires-action": {
"if": {
"properties": {
"relatedParty": {
"pattern": "tr\\d{2}"
}
},
"required": [
"relatedParty"
]
},
"then": {
"properties": {
"action": {
"pattern": "a"
}
},
"required": [
"action"
]
}
}
}
}
}
Then I've got 'No errors found. JSON validates against the schema' message. But the difference in 'action' property is still there.
Upvotes: 0
Views: 445
Reputation: 24399
The oneOf
keyword means one and only one of the schemas must validate successfully. The JSON Schema validator finds that both schemas fail and tells you the errors in both. Although it's obvious to a human looking at the schema that it's switching off of the value of the "relatedParty" property, the validator can't intuit your intention.
You can make your intention explicit to the validator using the if
/then
keywords.
{
"type": "object",
"properties": {
"relatedParty": {
"type": "string",
"oneOf": [
{ "pattern": "tr\\d{2}" },
{ "pattern": "er\\d{3}" }
]
}
},
"allOf": [
{ "$ref": "#/$defs/tr-requires-action" }
],
"$defs": {
"tr-requires-action": {
"if": {
"properties": {
"relatedParty": { "pattern": "tr\\d{2}" }
},
"required": ["relatedParty"]
},
"then": {
"properties": {
"action": { "pattern": "a" }
},
"required": ["action"]
}
}
}
}
(I had to make some assumptions about your data model, but hopefully you get the idea and can adapt the example.)
Upvotes: 1