json-schema-在所需属性中允许逻辑或

时间:2018-08-13 00:17:10

标签: jsonschema json-schema-validator json-schema-defaults

此问题的替代标题为“必需的属性组合”。

说我正在使用像这样的json模式:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "JSON schema for NLU (npm-link-up) library.",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "list", "packages", "deps"
  ],
   // ... 
}

我想做的是将“列表”,“包装”,“ deps”之一设为必填项。那应该是一个,但不能超过一个。

所以可能是这样的:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "JSON schema for NLU (npm-link-up) library.",
  "type": "object",
  "additionalProperties": false,
  "required": [
    {
      "min": 1,
      "max": 1,
      "selection":  ["list", "packages", "deps"]
    }
  ],
}

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "JSON schema for NLU (npm-link-up) library.",
  "type": "object",
  "additionalProperties": false,
  "required": [
    {
      "operator": "or",
      "selection": ["list", "packages", "deps"]
    }
  ],
}

这可能吗?

1 个答案:

答案 0 :(得分:2)

JSON模式中有四个布尔组合器关键字:

  • allOf-和
  • anyOf-或
  • oneOf-XOR(异或)
  • not-不

您想要的可以这样完成...

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "JSON schema for NLU (npm-link-up) library.",
  "type": "object",
  "additionalProperties": false,
  "oneOf": [
    { "required": ["list"] },
    { "required": ["packages"] },
    { "required": ["deps"] }
  ]
}