Pan*_*agi 1 schema json jsonschema
我正在使用JSON模式进行数据建模。我定义一个基Document
模式,即我以后使用来定义模型模式(例如Product
,Category
,User
等等)。
我这样做是因为我希望所有模型都继承某些结构/规则。例如每模型实例应当具有某些共同的性质(如,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
}
}
}
Run Code Online (Sandbox Code Playgroud)
$schema
,id
等等)?properties
每个模型架构包含一些常用的属性(id
,createdAt
,...),而不必在每个模型的架构定义来定义呢?JSON Schema不使用面向对象的范例,因此继承等概念无法很好地转换。JSON模式是约束的集合。像大多数人习惯的那样,它是减性的而不是加性的。这意味着在给定一个空模式的情况下,有效 JSON文档的集合就是所有 JSON文档的集合。添加关键字时,您将从有效的JSON文档集中减去。从集合中删除某些内容后,将无法重新添加。
因此,您可以使用合成来“扩展”模式,但是永远不能“覆盖”另一个模式定义的内容。
/模式/基础
{
"type": "object",
"properties": {
"foo": { "type": "string" }
"bar": { "type": "string" }
}
}
Run Code Online (Sandbox Code Playgroud)
/模式/扩展
{
"allOf": [{ "$ref": "/schema/base" }],
"properties": {
"baz": { "type": "string" }
}
}
Run Code Online (Sandbox Code Playgroud)
这里有一个简单的扩展,可以很好地与JSON Schema一起使用。
/模式/覆盖
{
"allOf": [{ "$ref": "/schema/base" }],
"properties": {
"bar": { "type": "integer" },
"baz": { "type": "boolean" }
}
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,两个模式都有一个/properties/bar
字段。如果您从继承的角度考虑这一点,那么您会误解这里发生的事情。在这种情况下,两个 “ / properties / bar”字段都必须有效。没有冲突可以解决。正如关键字所说,“所有”模式都必须有效。
希望可以为您提供足够的信息来解决您的问题并避免最常见的陷阱。
归档时间: |
|
查看次数: |
3465 次 |
最近记录: |