TMc*_*ell 2 python json jsonschema
我正在努力创建一个复杂的 JSON 模式,并且在验证“oneOf”构造时遇到问题。
我使用“oneOf”创建了一个非常简单的模式和一个简单的 JSON 文件来演示该问题。
JSON 架构:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"oneOf":[
{"properties": {"test1": {"type": "string"}}},
{"properties": {"test2": {"type": "number"}}}
]
}
Run Code Online (Sandbox Code Playgroud)
JSON 文件:
{
"test2":4
}
Run Code Online (Sandbox Code Playgroud)
当我使用 jsonschema.validate 验证 JSON 文件与架构时,我希望这是有效的。但是我得到的错误响应是:
Traceback (most recent call last):
File "TestValidate.py", line 11, in <module>
jsonschema.validate(instance=file, schema=schema, resolver=resolver)
File "C:\Python36\lib\site-packages\jsonschema\validators.py", line 899, in validate
raise error
jsonschema.exceptions.ValidationError: {'test2': 4} is valid under each of {'properties': {'test2': {'type': 'number'}}}, {'properties': {'test1': {'type': 'string'}}}
Failed validating 'oneOf' in schema:
{'$schema': 'http://json-schema.org/draft-07/schema#',
'oneOf': [{'properties': {'test1': {'type': 'string'}}},
{'properties': {'test2': {'type': 'number'}}}],
'type': 'object'}
On instance:
{'test2': 4}
Run Code Online (Sandbox Code Playgroud)
我不明白 'test2': 4 如何对 "test1": {"type": "string"} 有效。
使用以下 JSON,{"test2": 4}您的两个子模式oneOf都是有效的。
{"test2": 4}事实上,如果您尝试使用 schema验证 JSON {"properties": {"test1": {"type": "string"}}},它会起作用!为什么 ?因为字段test1不在您的 JSON 中。
要解决您的问题,您可以使用additionalProperties或required关键字。例如:
{
"type": "object",
"oneOf":[
{"properties": {"test1": {"type": "string"}}, "required": ["test1"]},
{"properties": {"test2": {"type": "number"}}, "required": ["test2"]}
]
}
Run Code Online (Sandbox Code Playgroud)
或者 ...
{
"type": "object",
"oneOf":[
{"properties": {"test1": {"type": "string"}}, "additionalProperties": false},
{"properties": {"test2": {"type": "number"}}, "additionalProperties": false}
]
}
Run Code Online (Sandbox Code Playgroud)