如何确保两个布尔属性的值永远不应该同时为真?

时间:2017-07-27 10:05:20

标签: json jsonschema json-schema-validator

鲍勃先生可能既快乐又悲伤,但不是两者兼而有之。他可能没有说明他的心情。因此,悲伤和快乐这两个属性都是可选的。

什么是json模式只能拒绝以下json

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

这是尝试失败的原因:

{
  "$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
            ]
          }
        }
      }
    ]
  }
}

以上架构在案件属性"悲伤"是真实的财产"快乐"不见了。

1 个答案:

答案 0 :(得分:1)

你非常接近。我所做的就是简化您的工作并添加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"]
  }
}