我有多个大json-schema
文件。许多模式文件都有一些共同的属性。
为了消除公共模式定义之间的冗余,将那些在单独的模式文件中分开并使用$ref
来引用单个 JSON 模式。
我所有模式文件的目录结构都像
/
|- schemas
|- components
|- page_layout.json
|- page.json
的内容page.json
是
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"examples": [],
"items": {
"type": "object",
"required": [],
"additionalProperties": false,
"properties": {
"type": {
"type": "string",
"enum": [
"page_layout", "banner_images"
]
},
"data": {
"type": "object"
}
},
"allOf": [
{
"if": {
"properties": {
"type": {
"const": "page_layout"
}
}
},
"then": {
"properties": {
"data": {
"$ref": "components/page_layout.json"
}
}
}
}
]
}
}
文件的内容page_layout.json
是
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {},
"type": "object",
"required": [],
"additionalProperties": false,
"properties": {
"backgroundColor": {
"type": "string"
},
"templateName": {
"type": "string",
"enum": ["linear", "square", "circle"]
}
}
}
结合这两个文件,要验证的示例 JSON 数据是
[
{
"type": "page_layout"
"data": {
"backgroundColor": "#ff00ff",
"templateName": "square"
}
},
{
"type": "banner_images"
"data": {
// Content for banner_images
}
}
]
的内容data
会根据type
值而变化。
我正在使用python jsonchema来验证 JSON 数据,验证代码是
import json
import jsonschema
import os
from json import JSONDecodeError
class SchemaValidator:
def __init__(self, category: str):
self.category = category
self.data = ''
def _schema(self):
schema_file = self.category.replace(' ', '_')
schema_path = os.path.join(os.path.dirname(__file__), 'json_schema', 'categories', '{}.json'.format(schema_file))
try:
with open(schema_path, 'r') as file:
return json.loads(file.read())
except FileNotFoundError:
raise Exception('Schema definition missing')
except JSONDecodeError:
raise Exception('Schema definition invalid')
def validate(self, data):
self.data = data
try:
status = jsonschema.validate(json.loads(data), self._schema())
except jsonschema.SchemaError as e:
raise Exception(e)
return status
但这会给$ref
文件带来错误,因为
unknown url type: 'components/page_layout.json'