6

I have two possible JSON objects for one request:

{
  "from": "string",
  "to": "string",
  "text": "string"
}

or

{
  "number": "integer",
  "text": "string"
}

In both cases "text" property is optional. Other properties are required (either "number, or both "from" and "to").

What will be the correct JSON schema to validate this?

Alexander Zhak
  • 9,140
  • 4
  • 46
  • 72
  • Possible duplicate of [JSON Schema: How do I require one field or another or (one of two others) but not all of them?](http://stackoverflow.com/questions/24023536/json-schema-how-do-i-require-one-field-or-another-or-one-of-two-others-but-no) – james.garriss Mar 27 '17 at 16:20

2 Answers2

15

Here is another solution that I think is a bit more clear. The dependencies clause ensures that "from" and "to" always come as a pair. Then the oneOf clause can be really simple and avoid the not-required boilerplate.

{
  "type": "object",
  "properties": {
    "from": { "type": "string" },
    "to": { "type": "string" },
    "number": { "type": "integer" },
    "text": { "type": "string" }
  },
  "dependencies": {
    "from": ["to"],
    "to": ["from"]
  },
  "oneOf": [
    { "required": ["from"] },
    { "required": ["number"] }
  ]
}
Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53
0

Finally managed to build the correct scheme.

{
  "definitions": {
    "interval": {
      "type": "object",
      "properties": {
        "from": {
          "type": "string"
        },
        "to": {
          "type": "string"
        },
        "text": {
          "type": "string"
        }
      },
      "required": ["from", "to"],
      "not": {
        "required": ["number"]
      }
    },
    "top": {
      "type": "object",
      "properties": {
        "number": {
          "type": "integer"
        },
        "text": {
          "type": "string"
        }
      },
      "required": ["number"],
      "allOf": [
        {
          "not": {
            "required": ["from"]
          }
        },
        {
          "not": {
            "required": ["to"]
          }
        }
      ]

    }
  },
  "type": "object",
  "oneOf": [
    {"$ref": "#/definitions/interval"},
    {"$ref": "#/definitions/top"}
  ]
}
Alexander Zhak
  • 9,140
  • 4
  • 46
  • 72