这里我尝试使用 jsonschema(Draft7Validator) 库验证我的 JSON 模式
验证架构:
{
"oneOf": [
{
"required": [
"Packet"
],
"properties": {
"Packet": {
"type": "object",
"required": [
"ShippingSerialID"
],
"properties": {
"ShippingSerialID": {
"type": "string",
"minLength": 1,
"maxLength": 2
}
}
}
}
},
{
"required": [
"Packet_2"
],
"properties": {
"Packet_2": {
"type": "object",
"required": [
"ShippingSerialID",
"Address"
],
"properties": {
"ShippingSerialID": {
"type": "string",
"minLength": 1,
"maxLength": 2
},
"Address": {
"type": "string",
"maxLength": 255
}
}
}
}
}
]
}
针对 JSON 数据:
{ 'name': 'William Shakespeare', 'address': 'Henley Street, England', 'Packet': {'ShippingSerialID': 'xyz'} }
通过返回错误:
[
{
'path': 'Packet.ShippingSerialID',
'message': "'xyz' is too long",
'validator': 'maxLength',
'validatorValue': 2
},
{
'path': '',
'message': "'Packet_2' is a required property",
'validator': 'required',
'validatorValue': [
'Packet_2'
]
}
]
这里对于第一个它会生成深度错误“Packet.ShippingSerialID”->“'xyz' is too long”,但对于第二个 od oneOf 它只会为根元素“'Packet_2' is a required property”生成错误。从中期待的是:
[
{
'path': 'Packet.ShippingSerialID',
'message': "'xyz' is too long",
'validator': 'maxLength',
'validatorValue': 2
},
{
'path': '',
'message': "'Packet_2' is a required property",
'validator': 'required',
'validatorValue': [
'Packet_2'
]
},
{
'path': 'Packet_2.Address',
'message': "'Address' is a required property",
'validator': 'required',
'validatorValue': [
'Address',
'ShippingSerialID'
]
},
{
'path': 'Packet_2.ShippingSerialID',
'message': "'xyz' is too long",
'validator': 'maxLength',
'validatorValue': 2
]
我怎样才能达到上述结果。
用于此的 Python 代码如下所示:
from jsonschema.validators import Draft7Validator
from jsonschema import draft7_format_checker
v = Draft7Validator(schema, format_checker=draft7_format_checker)
errors = sorted(v.iter_errors(json_data), key=lambda e: e.path)
errors_data = []
for error in errors:
for sub_error in sorted(error.context, key=lambda e: e.schema_path):
error_dict = {"path": ".".join(str(path) for path in sub_error.path)}
error_dict["message"] = sub_error.message
error_dict["validator"] = sub_error.validator
error_dict["validatorValue"] = sub_error.validator_value
errors_data.append(error_dict)
print(errors_data)