我正在创建复杂的JSON模式,并且在验证“ oneOf”构造时遇到问题。
我使用“ oneOf”和一个简单的JSON文件创建了一个非常简单的架构来演示该问题。
JSON模式:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"oneOf":[
{"properties": {"test1": {"type": "string"}}},
{"properties": {"test2": {"type": "number"}}}
]
}
JSON文件:
{
"test2":4
}
当我使用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}
我不明白'test2':4如何对“ test1”:{“ type”:“ string”}有效。
答案 0 :(得分:2)
使用以下JSON {"test2": 4}
,oneOf
中的两个子模式均有效。
实际上,如果您尝试使用模式{"test2": 4}
来验证JSON {"properties": {"test1": {"type": "string"}}}
,它就可以工作!为什么呢因为字段test1
不在您的JSON中。
要解决您的问题,您可以使用additionalProperties
或required
关键字。例如:
{
"type": "object",
"oneOf":[
{"properties": {"test1": {"type": "string"}}, "required": ["test1"]},
{"properties": {"test2": {"type": "number"}}, "required": ["test2"]}
]
}
或...
{
"type": "object",
"oneOf":[
{"properties": {"test1": {"type": "string"}}, "additionalProperties": false},
{"properties": {"test2": {"type": "number"}}, "additionalProperties": false}
]
}