JSON模式验证,如果有其他键,它们必须具有指定的名称和类型



我是json的初学者(我没有JS的历史(,直到最近我才遇到对json模式及其验证的需求。问题可以描述为:我的json中有5个键(属性(;A、 B、C、D、E,其中A、B和C是必需的,但D和E不是。特别是,D、E及其潜逃的每个组合都是有效的。但是,除了D和E之外,不能有任何其他键。下面是几个例子(集合中的项目表示对象的键(:

{A, B, C, D, E}  # valid
{A, B, C, D}     # valid
{A, B, C, E}     # valid
{A, B, C}        # valid
{A, B, D, E}     # invalid (C key is missing)
{A, B, C, D, Z}  # invalid (Z is not an allowed additional key)
{A, B, C, Z}     # invalid 

首先,我尝试编写自己的验证函数,这很有效,但在我们的项目中,我们已经在其他地方使用了jsonschema.validate,我的主管告诉我尝试用上述方法解决这个问题。这是一个接近解决问题的模式;

my_schema = {
"type": "object",
"maxProperties": 5,
"required": [
"A", "B", "C"
],
"properties": {
"A": {"type": ["boolean", "number"]},
"B": {"type": "array"},
"C": {"type": "number"},
"D": {"type": "string"},
"E": {"type": "string"}
}
}

然而,一个测试用例中的密钥是:

{A, B, C, D, Z}

正在作为有效的模式传递,而不应该。

您可以使用"additionalProperties": False而不是"maxProperties": 5

这里的代码:

import json
from jsonschema import Draft7Validator
my_schema = {
"type": "object",
"additionalProperties": False,
"required": [
"A", "B", "C"
],
"properties": {
"A": {"type": ["boolean", "number"]},
"B": {"type": "array"},
"C": {"type": "number"},
"D": {"type": "string"},
"E": {"type": "string"}
}
}
data = {
"A": True,
"B": [1, 2, 3],
"C": 1,
"D": "test",
"E": "test"
}
validator = Draft7Validator(my_schema)
validator.validate(data)

上面的将验证良好,而下面的将失败:

bad_data = {
"A": True,
"B": [1, 2, 3],
"C": 1,
"D": "test",
"Z": "test"
}
validator.validate(bad_data)

它会给你这个错误:

---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
/Users/danielsc/git/bwinf/41/Junior2/test.ipynb Cell 70 in <cell line: 10>()
1 bad_data = {
2     "A": True,
3     "B": [1, 2, 3],
(...)
6     "Z": "test"
7 }
9 validator = Draft7Validator(my_schema)
---> 10 validator.validate(bad_data)
File /usr/local/Caskroom/miniconda/base/envs/hugging/lib/python3.10/site-packages/jsonschema/validators.py:269, in create.<locals>.Validator.validate(self, *args, **kwargs)
267 def validate(self, *args, **kwargs):
268     for error in self.iter_errors(*args, **kwargs):
--> 269         raise error
ValidationError: Additional properties are not allowed ('Z' was unexpected)
Failed validating 'additionalProperties' in schema:
{'additionalProperties': False,
'properties': {'A': {'type': ['boolean', 'number']},
'B': {'type': 'array'},
'C': {'type': 'number'},
'D': {'type': 'string'},
'E': {'type': 'string'}},
'required': ['A', 'B', 'C'],
'type': 'object'}
On instance:
{'A': True, 'B': [1, 2, 3], 'C': 1, 'D': 'test', 'Z': 'test'}

相关内容

  • 没有找到相关文章

最新更新