繁体   English   中英

JSON 架构 oneOf 验证问题

[英]JSON Schema oneOf Validation Issue

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

当我验证 JSON 文件与使用 jsonschema.validate 的架构时,我希望这是有效的。 但是我得到以下错误响应:

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"} 有效。

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

实际上,如果您尝试使用架构{"properties": {"test1": {"type": "string"}}}验证 JSON {"test2": 4} ,它有效吗? 为什么 ? 因为现场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}
  ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM