跟进@chris-w 提供的答案,我想做同样的事情,jsonschema 3.2.0
但他的回答并没有完全涵盖我希望这个答案能帮助那些仍在寻求帮助但正在使用更新版本的人的包。
要使用该库扩展 JSON 模式,请执行以下操作:
- 创建基本架构:
base.schema.json
{
"$id": "base.schema.json",
"type": "object",
"properties": {
"prop": {
"type": "string"
}
},
"required": ["prop"]
}
- 创建扩展架构
extend.schema.json
{
"allOf": [
{"$ref": "base.schema.json"},
{
"properties": {
"extra": {
"type": "boolean"
}
},
"required": ["extra"]
}
]
}
- 创建要针对架构进行测试的 JSON 文件
data.json
{
"prop": "This is the property",
"extra": true
}
- 为基本模式创建 RefResolver 和 Validator 并使用它来检查数据
#Set up schema, resolver, and validator on the base schema
baseSchema = json.loads(baseSchemaJSON) # Create a schema dictionary from the base JSON file
relativeSchema = json.loads(relativeJSON) # Create a schema dictionary from the relative JSON file
resolver = RefResolver.from_schema(baseSchema) # Creates your resolver, uses the "$id" element
validator = Draft7Validator(relativeSchema, resolver=resolver) # Create a validator against the extended schema (but resolving to the base schema!)
# Check validation!
data = json.loads(dataJSON) # Create a dictionary from the data JSON file
validator.validate(data)
您可能需要对上述条目进行一些调整,例如不使用 Draft7Validator。这应该适用于单级引用(扩展基础的子级),您需要小心您的模式以及如何设置RefResolver
和Validator
对象。
PS 这是一个练习上述内容的片段。尝试修改data
字符串以删除所需的属性之一:
import json
from jsonschema import RefResolver, Draft7Validator
base = """
{
"$id": "base.schema.json",
"type": "object",
"properties": {
"prop": {
"type": "string"
}
},
"required": ["prop"]
}
"""
extend = """
{
"allOf": [
{"$ref": "base.schema.json"},
{
"properties": {
"extra": {
"type": "boolean"
}
},
"required": ["extra"]
}
]
}
"""
data = """
{
"prop": "This is the property string",
"extra": true
}
"""
schema = json.loads(base)
extendedSchema = json.loads(extend)
resolver = RefResolver.from_schema(schema)
validator = Draft7Validator(extendedSchema, resolver=resolver)
jsonData = json.loads(data)
validator.validate(jsonData)