skip to Main Content

I defined the following schema:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.com/schemas/test",
  "type": "object",
  "properties": {
    "A": {
      "type": "string"
    }
  },
  "oneOf": [
    {
      "properties": {
        "B": {
          "type": "integer"
        },
        "C": {
          "type": "boolean"
        }
      }
    },
    {
      "properties": {
        "D": {
          "type": "string"
        }
      }
    }
  ]
}

The idea is that the schema contains A, and either (B AND C) OR D. None of the elements are required (thus A is actually not part of the question/problem)

The following instance fails to validate:

{
  "A": "Hello",
  "D": "World"
}

It contains A (irrelevant, as not required anyway) and D, which should be covered by anyOf.

2

Answers


  1. I believe you want anyOf instead of oneOf, because oneOf checks for exactly one of the subschemas, but in your test instance you don’t have one of the subschemas. The docs are here: https://json-schema.org/understanding-json-schema/reference/combining#oneOf and you can test your schema here: https://json-schema.hyperjump.io/ which is where I find anyOf works in your case.

    Login or Signup to reply.
  2. I suggest the following approach. Define all your properties together and then add a constraint to express your requirement.

    {
      "properties": {
        "A": {},
        "B": {},
        "C": {},
        "D": {}
      },
      "oneOf": [
        { "required": ["B", "C"] },
        { "required": ["D"] }
      ]
    }
    

    Either "B" and "C" must be present or "D" must present, but not both. "A" may or may not be present with either option.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search