Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Schema: XOR on required fields

JSON Schemas have a required property, which lists the required fields in a JSON object. For example, the following (simplified) schema validates a call that sends a text message to a user:

{
  "type": "object",
  "properties": {
    "userId":    { "type": "string" },
    "text":      { "type": "string" },
  },
  "required": ["userId", "text"]
}

Suppose that I want to enable sending the message to multiple users, i.e. have either a userId field, or an array of userIds (but not both or neither). Is there a way to express such a condition in a JSON Schema?

Naturally, there are ways to overcome the problem in this case - for example, a userId array with a single element - but the general case is interesting and useful.

like image 750
Adam Matan Avatar asked Oct 27 '25 19:10

Adam Matan


1 Answers

You've probably sorted this out by now, but this will do the trick using oneOf on the type of the field.

{
  "type": "object",
  "properties": {
    "userId": {
      "oneOf": [
        {
          "type": "string"
        },
        {
          "type": "array",
          "items": {
            "type": "string"
          }
        }
      ]
    },
    "text": {
      "type": "string"
    }
  },
  "required": ["userId", "text"]
}
like image 148
Sam Sunde Avatar answered Oct 29 '25 10:10

Sam Sunde