What is the difference between "anyof" and "oneof" in z schema?

Somnath picture Somnath · Dec 2, 2015 · Viewed 9.8k times · Source

Its looking like both works fine with my input validation code. Then what is the exact difference?

Schema with oneof

[{
  "id": "MyAction",
  "oneOf": [{ "$ref": "A1" },
            { "$ref": "A2" }]
 },
 {
  "id": "A1",
  "properties": {
      "class1": { "type": "string"},
      "class2": { "type": "string"}
   }
 },
 {
  "id": "A2",
  "properties": {
      "class2": { "type": "string"},
      "class3": { "type": "string"}
   }
 }
]

Schema with anyof

    [{
  "id": "MyAction",
  "anyOf": [{ "$ref": "A1" },
            { "$ref": "A2" }]
 },
 {
  "id": "A1",
  "properties": {
      "class1": { "type": "string"},
      "class2": { "type": "string"}
   }
 },
 {
  "id": "A2",
  "properties": {
      "class2": { "type": "string"},
      "class3": { "type": "string"}
   }
 }
]

Answer

T.J. Crowder picture T.J. Crowder · Dec 2, 2015

If you look at the JSON Schema documentation, it says:

5.5.4. anyOf

5.5.4.1. Valid values

This keyword's value MUST be an array. This array MUST have at least one element.

Elements of the array MUST be objects. Each object MUST be a valid JSON Schema.

5.5.4.2. Conditions for successful validation

An instance validates successfully against this keyword if it validates successfully against at least one schema defined by this keyword's value.

5.5.5. oneOf

5.5.5.1. Valid values

This keyword's value MUST be an array. This array MUST have at least one element.

Elements of the array MUST be objects. Each object MUST be a valid JSON Schema.

5.5.5.2. Conditions for successful validation

An instance validates successfully against this keyword if it validates successfully against exactly one schema defined by this keyword's value.

Note my emphasis in the above. anyOf means the item must validate against at least one (but possibly more than one) of the schemas. oneOf means it must validate against only one of the schemas.