我正在使用 JSON 模式进行数据建模。我定义了一个基数 Document
模式,我稍后用它来定义模型模式(例如 Product
、 Category
、 User
等)。
我这样做是因为我希望所有模型都继承某些结构/规则。例如,每个模型实例都应该具有某些公共(public)属性(例如,id
、createdAt
、updatedAt
)。在 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
}
}
}
$schema
、 id
等) ? properties
每个模型模式包含一些公共(public)属性(id
,createdAt
,...),而不必在每个模型模式定义中定义它们? 最佳答案
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/