我已经使用jsonschema
安装了pip install jsonschema
。
from jsonschema import validate
schema_data = {
"type" : "object",
"properties" : {
"price" : {"type" : "number"},
"name" : {"type" : "string"},
"additional" : {"type" : "number"},
},
}
json_data = {"name" : "Eggs", "price" : 34.99, "new": 90}
我在schema_data
和json_data
以上,只是在验证数据类型。
这里additional
是schema_data
中缺少的json_data
中的一个额外字段,而{{1}中却没有{{1}中存在的new
}}。
如何列出json_data
中缺少 schema_data
的缺少字段,而additional
json_data
>?
答案 0 :(得分:2)
在JSON模式中,默认情况下不需要属性 ,您的模式所做的只是声明如果该属性存在,它们必须是哪种类型。因此,要进行验证以标记additional
丢失,您需要先通过添加以下名称的required
列表来将该键标记为a required property:
schema_data = {
"type" : "object",
"properties" : {
"price" : {"type" : "number"},
"name" : {"type" : "string"},
"additional" : {"type" : "number"},
},
"required": ["price", "name", "additional"]
}
由于缺少additional
,现在验证将使您的JSON数据失败:
>>> validate(json_data, schema_data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../site-packages/jsonschema/validators.py", line 541, in validate
cls(schema, *args, **kwargs).validate(instance)
File "/.../site-packages/jsonschema/validators.py", line 130, in validate
raise error
jsonschema.exceptions.ValidationError: 'additional' is a required property
Failed validating 'required' in schema:
{'properties': {'additional': {'type': 'number'},
'name': {'type': 'string'},
'price': {'type': 'number'}},
'required': ['price', 'name', 'additional'],
'type': 'object'}
On instance:
{'name': 'Eggs', 'new': 90, 'price': 34.99}
要使添加 more 键无效,需要将additionalProperties
设置为false
;默认是允许额外的属性:
schema_data = {
"type" : "object",
"properties" : {
"price" : {"type" : "number"},
"name" : {"type" : "string"},
"additional" : {"type" : "number"},
},
"required": ["price", "name", "additional"],
"additionalProperties": False
}
但是,在缺少additional
的情况下,使用new
时找不到附加的validate()
键,因为发现的第一个错误是异常。
要获取所有个模式验证错误,请为模式创建一个验证器对象,然后使用IValidator.iter_errors()
method列出找到的所有错误:
from json_schema.validators import validator_for
validator = validator_for(schema_data)(schema_data) # get class, create instance
for error in validator.iter_errors(json_data):
print(error)
现在您将获得有关每个错误的信息:
'additional' is a required property
Failed validating 'required' in schema:
{'additionalProperties': False,
'properties': {'additional': {'type': 'number'},
'name': {'type': 'string'},
'price': {'type': 'number'}},
'required': ['price', 'name', 'additional'],
'type': 'object'}
On instance:
{'name': 'Eggs', 'new': 90, 'price': 34.99}
Additional properties are not allowed ('new' was unexpected)
Failed validating 'additionalProperties' in schema:
{'additionalProperties': False,
'properties': {'additional': {'type': 'number'},
'name': {'type': 'string'},
'price': {'type': 'number'}},
'required': ['price', 'name', 'additional'],
'type': 'object'}
On instance:
{'name': 'Eggs', 'new': 90, 'price': 34.99}
循环中的每个error
对象都是一个ValidatorError
exception object,它具有一系列属性,可以帮助您用代码准确地找出问题所在。