jonathangersam
jonathangersam

Reputation: 1147

How Do I Require that a Sub-Property Must Exist Using JSON Schema?

In JSON Schema, I can use require to ensure that a property exists on the same level of the hierarchy, but I'm having trouble validating for nested ones.

Suppose I have following JSON Schema:

{
    "type": "object",
    "properties": {
        "my_type": {
            "type": "string"
        },
        "t1_data": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                }
            }
        },
        "t2_data": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                }
            }
        }
    }
}

How would I specify the following validations?

I've tried using the require and anyOf constructs but I could only get them to work at the same level of the hierarchy.

Thanks,

Upvotes: 0

Views: 364

Answers (1)

Clemens
Clemens

Reputation: 1817

A possible solution is to combine allOf and if-then. It is a little bit verbose but I am not aware of any shorter way. Here is the schema for the case "type1":

{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "description": "JSON schema generated with JSONBuddy https://www.json-buddy.com",
  "type": "object",
  "properties": {
    "my_type": {
      "type": "string"
    },
    "t1_data": {
      "type": "object",
      "properties": {
        "id": {
          "type": "string"
        }
      }
    },
    "t2_data": {
      "type": "object",
      "properties": {
        "id": {
          "type": "string"
        }
      }
    }
  },
  "allOf": [
    {
      "if": {
        "properties": {
          "my_type": {
            "const": "type1"
          }
        }
      },
      "then": {
        "properties": {
          "t1_data": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string"
              }
            },
            "required": [ "id" ]
          }
        }
      }
    }
  ]
}

"type2" would be quite the same as next schema in the allOf array.

Upvotes: 3

Related Questions