我有一个JSON模式,我希望在其中定义我项目的所有对象我希望能够通过这个JSON模式(使用“jsonschema”python库)验证我的所有对象。。为了避免重复,我不想为每个对象创建一个模式文件
考虑下面的说明性玩具实例(^ {CD1>}):
{
"$schema":"https://json-schema.org/draft/2020-12/schema",
"$id":"https://example.com/toy-example.json",
"title": "JSON Schema",
"description": "JSON Schema deifning objects a,b and c",
"type": "object",
"$defs":{
"a": {
"$id": "#a",
"type": "object",
"properties": {
"c_array": {
"type": "array",
"items": {
"$ref": "#/$defs/c"
}
}
},
"required": ["c_array"]
},
"b": {
"$id": "#b",
"type": "object",
"properties": {
"c": {"ref": "#/$defs/c"}
},
"required": ["c"]
},
"c": {
"$id": "#c",
"type": "number",
"minimum": 0
}
},
"allOf": [{"$ref": "#/$defs/a"}]
}
以下代码用于验证“a”对象(由于底部添加了“allOf”指令):
import jsonschema, json
with open("toy-schema.json", "r") as f: schema = json.load(f)
a = {"c_array": [1,2,3]}
jsonschema.validate(a, schema) ## is valid, correctly stays silent
a = {"c_array": [-1,2,3]}
jsonschema.validate(a, schema) ## is invalid (-1 < 0), correctly raises ValidationError
我还希望能够验证对象“b”,理想情况下使用如下语法:
import jsonschema, json
with open("toy-schema.json", "r") as f: schema = json.load(f)
b = {"c": 1}
jsonschema.validate(b, schema, "/$defs/#b") ## valid
b = {"c": -1}
jsonschema.validate(b, schema, "/$defs/#b") ## invalid
我相信这样做可以避免任何模式定义的重复
目前没有回答
相关问题 更多 >
编程相关推荐