4

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.

Adam Matan
  • 128,757
  • 147
  • 397
  • 562

2 Answers2

2

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"]
}
Sam Sunde
  • 151
  • 7
1

Not elegant at all, but I think you can hack it out from allOf and oneOf. Something like:

 {
   "allOf" : [
      {
        "type" : "object",
        "properties" : {
          // base properties come here
        }
      },
      "oneOf" : [
        {
        "properties" : {
             "userIds" : {"type" : "array"}
          },
          "required" : ["userIds"]
        },
        {
          "properties" : {
             "userId" : {"type" : "number"}
          },
          "required" : ["userId"]
        }
      ]
   ]
}
erosb
  • 2,943
  • 15
  • 22