[英]JSON Schema oneOf Validation Issue
I am working on creating a complex JSON schema and am having issues with validating a "oneOf" construction.我正在创建一个复杂的 JSON 架构,并且在验证“oneOf”构造时遇到问题。
I have created a very simple schema using "oneOf" and a simple JSON file to demonstrate the issue.我使用“oneOf”和一个简单的 JSON 文件创建了一个非常简单的模式来演示该问题。
JSON Schema: JSON 架构:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"oneOf":[
{"properties": {"test1": {"type": "string"}}},
{"properties": {"test2": {"type": "number"}}}
]
}
JSON File: JSON 文件:
{
"test2":4
}
When I validate the JSON file versus the schema using jsonschema.validate I expect for this to be valid.当我验证 JSON 文件与使用 jsonschema.validate 的架构时,我希望这是有效的。 However I get the error response of:
但是我得到以下错误响应:
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}
I don't understand how 'test2': 4 can be valid against "test1": {"type": "string"}.我不明白 'test2': 4 如何对 "test1": {"type": "string"} 有效。
With the following JSON {"test2": 4}
both sub-schemas in your oneOf
are valid.使用以下 JSON
{"test2": 4}
oneOf
中的两个子模式都是有效的。
Indeed if you try to validate JSON {"test2": 4}
with schema {"properties": {"test1": {"type": "string"}}}
, it works?实际上,如果您尝试使用架构
{"properties": {"test1": {"type": "string"}}}
验证 JSON {"test2": 4}
,它有效吗? Why ?为什么 ? Because field
test1
is not in your JSON.因为现场
test1
不在您的 JSON 中。
To fix your issue you can either use additionalProperties
or required
keywords.要解决您的问题,您可以使用
additionalProperties
或required
的关键字。 For instance:例如:
{
"type": "object",
"oneOf":[
{"properties": {"test1": {"type": "string"}}, "required": ["test1"]},
{"properties": {"test2": {"type": "number"}}, "required": ["test2"]}
]
}
or...或者...
{
"type": "object",
"oneOf":[
{"properties": {"test1": {"type": "string"}}, "additionalProperties": false},
{"properties": {"test2": {"type": "number"}}, "additionalProperties": false}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.