jsonschema 扩展并且没有额外的属性

ram*_*min 5 jsonschema python-jsonschema

我正在使用 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
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

Rel*_*ual 6

不幸的是,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"
        }
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • JSON Schema 草案(版本)2019-09 及更高版本具有“unevaluatedProperties”,它可以“透视”应用程序,例如“allOf”和“$ref”。它比这更复杂一些,但在大多数情况下,这正是人们可能需要的。 (2认同)