0

I've recently learned (this, this, and this, among other resources) how to use the oneOf keyword to declare JSON validity only when one among many elements is present at the same nesting level. E.g., the following schema:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "req1": {
      "type": "string"
    },
    "req2": {
      "type": "string"
    },
    "obj": {
      "type": "object",
      "properties": {
        "req1": {
          "type": "string"
        }
      }
    }
  },
  "oneOf": [
    { "required": ["req1"] },
    { "required": ["req2"] }
  ]
}

...ensures that the following are valid json:

{ "req1": "foo", "obj": { "req1": "foo" } }
{ "req2": "foo", "obj": { "req1": "foo" } }

...and the following is not because both req1 and req2 are present, rather than one of req1 and req2:

{ "req1": "foo", "req2": "foo", "obj": { "req1": "foo" } }

I'm failing at extrapolating from this example to enforcing the "one-of required" concept to elements at different nesting levels. E.g. how can I enforce that one of req1 and obj.req1 are required?

StoneThrow
  • 5,314
  • 4
  • 44
  • 86

1 Answers1

0

E.g. how can I enforce that one of req1 and obj.req1 are required?

...
"oneOf": [
  {
    "required": [ "req1" ]
  },
  {
    "required": [ "obj" ],
    "properties": {
      "obj": {
        "type": "object",
        "required": [ req1 ]
      }
    }
  }
]
Ether
  • 53,118
  • 13
  • 86
  • 159