[JSON Schema oneof Validation Issue

问题描述 投票:1回答:1

我正在创建一个复杂的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”}有效。

python json jsonschema
1个回答
0
投票

使用以下JSON {"test2": 4},您的oneOf中的两个子模式都是有效的。

事实上,如果您尝试使用架构{"test2": 4}验证JSON {"properties": {"test1": {"type": "string"}}},那么它将起作用!为什么呢因为字段test1不在您的JSON中。

要解决您的问题,您可以使用additionalPropertiesrequired关键字。例如:

{
  "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}
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.