Nilesh Nilesh - 1 year ago 50
JSON Question

How to ensure value of both boolean properties should never be true simultaneously?

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.

Answer Source

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"]
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download