Json to validate an array of objects with anyOf and oneOf requirements

I am trying to define a json schema to restrict the properties of objects contained in an array.

What I still have:

{ "title":"myCollection", "properties":{ "things":{ "type":"array", "items":[{ "title":"thingObj", "type":"object", "properties":{ "name":{ "type":"string" }, "code":{ "type":"string" }, "type":{ "type":"string", "enum":["dog","cat"] }, "rate":{ "type":"number" }, "value":{ "type":"number" } }, "anyOf":[{ "properties":{ "name":{ "type":"string" } },"required":["name"] },{ "properties":{ "code":{ "type":"string" } },"required":["code"] },{ "properties":{ "type":{ "type":"string", "enum":["new","existing"] } },"required":["type"] }], "oneOf":[{ "properties":{ "rate":{ "type":"number" } }, "required":["rate"] },{ "properties":{ "value":{ "type":"number" } }, "required":["value"] }], "additionalProperties":false }] } } } 

Now set the following jsonobj:

 { "things": [ { "name": "tabby", "code": "meeow", "type": "cat", "value": 20 }, { "name": "k9", "code": "woofer", "type": "dog", "rate": 15 } ] } 

This json schema check mechanism provides a valid answer, but this check seems to apply only to the first element of the array. If you delete all fields included in the anyOf clause or the oneOf clause in the first element, then the check fails. The same thing on the second element of the array does not cause the desired failure. How can I guarantee that validation is performed against each element of the array?

+6
source share
1 answer

This is because you (accidentally) use a "tuple". This is included when the "items" value is an array and matches the schemas for specific items in the array.

If you change the "items" (in your schema) as just a schema (and not an array of schemas), then it will check all the elements the same way.

+13
source

Source: https://habr.com/ru/post/958493/


All Articles