已创建以下架构:
{
"type": "object",
"properties": {
"name": {
"type": "string",
"enum": [
"full",
"partial"
]
}
},
"required": [
"name"
],
"if": {
"properties": {
"name": {
"const": "full"
}
}
},
"then": {
"properties": {
"status": {
"type": "string",
"enum": [
"success",
"failure"
]
}
},
"required": [
"status"
]
},
"else": {
"properties": {
"status": {
"type": "string",
"enum": [
"success",
"failure",
"partial success"
]
},
"message": {
"type": "string"
},
"created": {
"type": "array",
"items": [
{
"type": "integer"
}
]
},
"deleted": {
"type": "array",
"items": [
{
"type": "integer"
}
]
}
},
"required": [
"name",
"status",
"created",
"deleted"
]
}
}
我尝试使用两种json,基于键“name”,键将有不同的子验证——“full”和“partial”
因此,两个可能的示例有效json是:
当名称为“full”时
{"name": "full", "status": "success"}
当名称为“部分”时
{
"name": "partial",
"status":"success",
"created": [6],
"deleted": [4]
}
在python中使用此模式进行验证时,并不是在if/then/else中验证该部分
validator = Validator(json.load(open(path, 'r')))
validator.validate({"name": "full"})
[]
validator.validate({"name": "full", "status": "success"})
[]
它给出两个都有效,而第一个应该无效
同样,对于第二个json,对于无效的json也不会失败:
validator.validate({"name": "partial"})
[]
validator.validate({"name": "partial", "stauts": "success", "created": [6], "deleted": [4]})
[]
Python验证程序代码:
class Validator(object):
def __init__(self, schema):
self.schema = schema
def validate(self, json):
validator = Draft4Validator(self.schema)
errors = sorted(validator.iter_errors(json), key=str)
return errors
您使用的是JSON模式草案4验证程序,但conditional sub-schemas仅添加到草案7中
在测试here时,模式本身工作良好。您只需要将versioned validator从
Draft4Validator
更改为Draft7Validator
相关问题 更多 >
编程相关推荐