5

我正在使用 jsonschema 来验证条目类型,这些条目类型描述了(给定类型的)条目是如何显示的。这些条目可以有页面并分为多个方面。

页面和方面都可以设置条件,我想重用基本模式,即使方面的条件可以具有页面条件没有的 2 个其他属性。

这是我经常遇到的普遍问题。我想扩展一个模式,同时能够在所有情况下将“additionalProperties”设置为 false。

我也看不到用 anyOf 修复它的可能性,allOf 没有重复。

还是我应该放弃additionalProperties或接受重复项?


  {
    "$comment": "page condition",
    "type": "object",
    "properties": {
      "condition": {
        "type": "object",
        "properties": {
          "aspect": {
            "type": "string"
          },
          "value": {
            "type": "string"
          },
          "compare": {
            "type": "string"
          }
        },
        "required": [
          "aspect",
          "value"
        ],
        "additionalProperties": false
      }
    }
  }

...
  {
    "$comment": "aspect condition",
    "type": "object",
    "properties": {
      "condition": {
        "type": "object",
        "properties": {
          "aspect": {
            "type": "string"
          },
          "value": {
            "type": "string"
          },
          "compare": {
            "type": "string"
          },
          "disabled_text": {
            "type": "string"
          },
          "default_pass": {
            "type": "boolean"
          }
        },
        "required": [
          "aspect",
          "value"
        ],
        "additionalProperties": false
      }
    }
  }
4

1 回答 1

7

不幸的是,draft-7 JSON Schema 无法解决这个问题。

您需要additionalProperties: false从您希望引用的任何架构中删除。

一种减少重复的方法是,在您的引用模式中,重新定义属性,但仅使用true. 这意味着验证部分仍然发生在引用的模式本身中。

我在这张幻灯片的最近一次演讲中将其作为一个示例问题来解决: https ://stoic-agnesi-d0ac4a.netlify.com/32

结果模式的一部分:

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "definitions": {
    "geneticsPatient": {
      "type": [
        "object"
      ]
    },
    "regularPatient": {
      "type": [
        "object"
      ]
    }
  },
  "properties": {
    "patient": {
      "additionalProperties": false,
      "properties": {
        "name": true,
        "phenotypicFeatures": true,
        "genomicFeatures": true
      },
      "allOf": [
        {
          "$ref": "#/definitions/regularPatient"
        },
        {
          "$ref": "#/definitions/geneticsPatient"
        }
      ]
    }
  }
}

在最近发布的 2019-09 草案中,我们添加了一个新关键字,尽管您仍然不需要additionalProperties: false在引用的架构中定义。

您可以从我的其他一些幻灯片中了解更多信息:https ://speakerdeck.com/relequestual/json-schema-draft-8-to-vocabularies-and-beyond

于 2019-11-11T09:21:05.837 回答