jsonvalidationjsonschemajson-schema-validator

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


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"}
   }
 }
]

Solution

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

    anyOf:

    ...

    An instance validates successfully against this keyword if it validates successfully against at least one schema defined by this keyword's value. Note that when annotations are being collected, all subschemas MUST be examined so that annotations are collected from each subschema that validates successfully.

    oneOf:

    ...

    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.