0

Mr Bob can be either happy or sad but not both. It is possible that he does not specify his mood. Hence both properties, sad and happy are optional.

What would be a json schema for rejecting only the following json

{
  "name": "Bob",
  "sad": true,
  "happy": true
}

Here's the failed attempt :

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "happy": {
      "type": "boolean",
      "default": false
    },
    "sad": {
      "type": "boolean",
      "default": false
    }
  },
  "not": {
    "allOf": [
      {
        "properties": {
          "happy": {
            "enum": [
              true
            ]
          }
        }
      },
      {
        "properties": {
          "sad": {
            "enum": [
              true
            ]
          }
        }
      }
    ]
  }
}

Above schema fails in case property "sad" is true and property "happy" is missing.

Nilesh
  • 2,089
  • 3
  • 29
  • 53
  • In that case wouldn't it make more sense to have a `mood` that can be happy, sad or null? – jonrsharpe Jul 27 '17 at 10:06
  • Hi @jonrsharpe No we cant change the model. Its like that.. :( You can take it as *How to ensure value of both properties should never be true simultaneously?* – Nilesh Jul 27 '17 at 10:13

1 Answers1

1

You're pretty close. All I did was simplify what you have and add required.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "happy": {
      "type": "boolean",
      "default": false
    },
    "sad": {
      "type": "boolean",
      "default": false
    }
  },
  "not": {
    "properties": {
      "happy": { "enum": [true] },
      "sad": { "enum": [true] }
    },
    "required": ["happy", "sad"]
  }
}
Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53