json - 如何在 JSON 模式中扩展模式?

标签 json schema jsonschema

我正在使用 JSON 模式进行数据建模。我定义了一个基数 Document模式,我稍后用它来定义模型模式(例如 ProductCategoryUser 等)。

我这样做是因为我希望所有模型都继承某些结构/规则。例如,每个模型实例都应该具有某些公共(public)属性(例如,idcreatedAtupdatedAt)。在 OOP 术语中:Product extends Document因此它继承了它的实例属性。在模式术语中(我认为)Document是用于创建模型模式的元模式。

我已将 Document 模式定义如下:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "id": "http://example.com/schemas/document.json#",
  "title": "Document",
  "type": "object",
  "additionalProperties": false,
  "required": ["type", "name", "fields"],
  "properties": {
    "type": {
      "constant": "document"
    },
    "name": {
      "type": "string"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "readOnly": {
      "type": "boolean"
    },
    "properties": {
      // common properties 
      // model-specific properties
    }
  }
}
  • 如何指定 Document 元模式“扩展”基本 JSON 模式(draft-07),这样我就不必定义草稿的所有属性( $schemaid 等) ?
  • 如何指定 properties每个模型模式包含一些公共(public)属性(idcreatedAt,...),而不必在每个模型模式定义中定义它们?
  • 最佳答案

    JSON Schema 不使用面向对象的范例,因此继承之类的概念不能很好地翻译。 JSON Schema 是一组约束。它是减法而不是像大多数人习惯的那样加法。这意味着给定一个空模式,有效 JSON 文档的集合是所有 JSON 文档的集合。当您添加关键字时,您正在从一组有效的 JSON 文档中减去。一旦从集合中移除某些东西,就不能再添加回来。
    因此,您可以使用组合来“扩展”模式,但永远不能“覆盖”另一个模式定义的内容。
    让我们看一个没有冲突属性的简单扩展示例。
    /schema/base

    {
      "type": "object",
      "properties": {
        "foo": { "type": "string" },
        "bar": { "type": "string" }
      }
    }
    
    /schema/扩展
    {
      "allOf": [{ "$ref": "/schema/base" }],
      "properties": {
        "baz": { "type": "string" }
      }
    }
    
    这适用于 JSON Schema。现在让我们看一个具有冲突属性定义的示例。
    /架构/覆盖
    {
      "allOf": [{ "$ref": "/schema/base" }],
      "properties": {
        "bar": { "type": "integer" },
        "baz": { "type": "boolean" }
      }
    }
    
    在本例中,两个模式都有 /properties/bar field 。如果您从继承的角度考虑这一点,您将误解这里发生的事情。在这种情况下,两个“/properties/bar”字段都必须有效。没有冲突需要解决。正如关键字所说,“所有”模式必须有效。由于bar不可能既是整数又是字符串,任何文档都不会针对 /schema/override 进行验证.
    希望这可以为您提供足够的信息来解决您的问题并避免最常见的问题。

    关于json - 如何在 JSON 模式中扩展模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52566472/

    相关文章:

    javascript - AngularJS 从 postdata 中删除数据

    php - 元素 'foo' : This element is not expected. 预期为 ( {http ://www. example.com}foo )

    ios - 如何解析具有多个值的 json?

    c++ - 使用 jsoncpp 时从 JSON 中剥离私有(private)数据的最佳方法

    database - 如何在 Prisma 模式中表示额外的关系列?

    数组内的 JSON-Schema 模式重复

    jsonschema - 如何使用 JSON 模式验证器防止某些字段基于另一个字段值

    java - 如何设置Json schema的类型?

    javascript - 检索纯文本 JSON,插入到 JavaScript

    XML Schema (XSD) 验证工具?