XOR logic in JSON schema for a list of boolean items

坚强是说给别人听的谎言 提交于 2019-12-08 05:57:48

问题


I faced a problem with validating a list of boolean values. My input is:

[true,true,false]

and it should not verify this because only lists with one and only one true value, should be true. At the moment my schema does a sort of inclusive OR by accepting one or more true values, but not all:

{
  "type": "array",
  "items": {
    "$ref": "#/definitions/_items"
  },
  "$ref": "#/definitions/xor",
  "definitions": {
    "xor": {
      "oneOf": [
        {
          "$ref": "#/definitions/or"
        },
        {
          "$ref": "#/definitions/and"
        }
      ]
    },
    "_items": {
      "enum": [
        true,
        1
      ]
    },
    "or": {
      "not": {
        "type": "array",
        "items": {
          "not": {
            "$ref": "#/definitions/_items",
            "maximum": 1,
            "minimum": 1
          }
        }
      }
    },
    "and": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/_items"
      }
    }
  }
}

As you can see, I have tried to solve it with maximum and minimum attributes but they don't seem to affect the outcome.

One truth table would correctly be:

[true,true,false] => false

[true,true,true] => false

[true,false,false] => true

[false,false,false] => false

[false,true,false] => true

[false,false,true] => true

[true,false,true] => false

[false,true,true] => false


回答1:


You can explicitly use your truth table:

{
  "type": "array",
  "minItems": 3,
  "maxItems": 3,
  "anyOf": [
    {
      "items": [
        { "enum": [true] },
        { "enum": [false] },
        { "enum": [false] }
      ]
    },
    {
      "items": [
        { "enum": [false] },
        { "enum": [true] },
        { "enum": [false] }
      ]
    },
    {
      "items": [
        { "enum": [false] },
        { "enum": [false] },
        { "enum": [true] }
      ]
    }
  ]
}

If you want a general solution with more than 3 items it quickly gets out of hand.

draft-06 defines keyword "contains" that allows to validate that at least one items matches some schema (but not exactly one), but as far as I know the standard JSON-schema keywords don't allow what you want.

You can either generate schema programmatically (for any fixed number of items) or validate without schema.



来源:https://stackoverflow.com/questions/42026162/xor-logic-in-json-schema-for-a-list-of-boolean-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!