gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:02:52 24 4
gpt4 key购买 nike

我正在使用 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com