Draft 04 | Draft 06 | Draft 07 | Draft 2019-09 | Draft 2020-12 |
The 3 keywords AnyOf, AllOf and OneOf work in the same way, but have slightly different logic for each.
Essentially each can contain a number of schemas, each schema is validated against the instance value.
The AllOf, AnyOf, OneOf nodes are all optional, and a schema can contain any combination of them.
This example shows how it's possible to create 2 versions of an address, in this case a US and UK style.
The AddressLine1, AddressLine2 & City properties are common to both.
The OneOf node means that the instance object must also validate against just one of the 2 contained schemas.
The first schema stipulates that the instance object must contain a ZipCode and may also have a State.
The second schema stipulates that the instance object must contain a PostCode and may also have a County.
Notice in the OneOf schemas the ZipCode & PostCode are required.
If these were left as optional fields then the schemas would validate against any instance object (due to the Additional Properties not), and if both of them validated the OneOf clause would fail.
Example |
Copy Code
|
---|---|
{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "title": "My schema", "additionalProperties": true, "properties": { "AddressLine1": { "type": "string" }, "AddressLine2": { "type": "string" }, "City": { "type": "string" } }, "required": [ "AddressLine1" ], "oneOf": [ { "type": "object", "properties": { "State": { "type": "string" }, "ZipCode": { "type": "string" } }, "required": [ "ZipCode" ] }, { "type": "object", "properties": { "County": { "type": "string" }, "PostCode": { "type": "string" } }, "required": [ "PostCode" ] } ] } |
The following data is valid as it validates against the core schema and the first 'OneOf' schema (the second 'OneOf' schema requires that a PostCode be present, so this one does not validate).
Valid Json Data |
Copy Code
|
---|---|
{ "AddressLine1" : "Microsoft Corporation", "AddressLine2" : "One Microsoft Way", "City" : "Redmond", "State" : "WA", "ZipCode" : "98052-7329" } |