【问题标题】:jsonschema: Abstract Data Type and correct error messagejsonschema:抽象数据类型和正确的错误信息
【发布时间】:2021-11-26 14:44:37
【问题描述】:

我正在像这样使用jsonschema Python 库:

import jsonschema

schema = {
    "type": "object",
    "oneOf": [
        {
            "type": "object",
            "additionalProperties": False,
            "required": ["key"],
            "properties": {"key": {"enum": ["foo"], "type": "string"}},
        },
        {
            "type": "object",
            "additionalProperties": False,
            "required": ["key", "baritem"],
            "properties": {
                "key": {"enum": ["bar"], "type": "string"},
                "baritem": {"type": "string"},
            },
        },
    ],
}

我可以验证正确的数据:

jsonschema.validate({"key": "bar", "baritem": "ok"}, schema)

但是如果一个属性丢失,如果失败(如预期的那样),但有一个奇怪的错误信息:

jsonschema.validate({"key": "bar"}, schema)
Traceback (most recent call last):
  File "valid.py", line 29, in <module>
    jsonschema.validate({"key": "bar"}, schema)
  File "/home/david/.pyenv/versions/3.7.11/lib/python3.7/site-packages/jsonschema/validators.py", line 934, in validate
    raise error
jsonschema.exceptions.ValidationError: 'bar' is not one of ['foo']

Failed validating 'enum' in schema[0]['properties']['key']:
    {'enum': ['foo'], 'type': 'string'}

On instance['key']:
    'bar'

我的第一个问题是:定义JSON 模式是否正确,尤其是使用enum 定义key 的部分?

我的第二个问题是:有没有办法用jsonschema 正确定义像这样的抽象数据类型,即告诉jsonschema 根据key 属性选择oneOf 中列出的object,并基于此对象验证其余属性?

【问题讨论】:

    标签: python jsonschema


    【解决方案1】:

    您可以根据if/then/elsedependentSchemas 的其他属性的值选择要应用的子模式:https://json-schema.org/understanding-json-schema/reference/conditionals.html

    【讨论】:

    • 看起来不错,谢谢!
    【解决方案2】:

    目前,我的解决方案是选择自己使用的特定架构:

    import jsonschema
    from jsonschema.exceptions import ValidationError
    
    schema_foo = {
        "type": "object",
        "additionalProperties": False,
        "required": ["key"],
        "properties": {"key": {"enum": ["foo"], "type": "string"}},
    }
    
    schema_bar = {
        "type": "object",
        "additionalProperties": False,
        "required": ["key", "baritem"],
        "properties": {
            "key": {"enum": ["bar"], "type": "string"},
            "baritem": {"type": "string"},
        },
    }
    
    schema = {
        "type": "object",
        "oneOf": [
            schema_foo,
            schema_bar,
        ],
    }
    
    schema_by_key = {"foo": schema_foo, "bar": schema_bar}
    
    data = {"key": "bar"}
    
    try:
        key = data["key"]
    except KeyError:
        raise ValidationError("key is missing")
    
    try:
        specific_schema = schema_by_key[key]
    except KeyError:
        raise ValidationError("key is invalid")
    
    jsonschema.validate(data, specific_schema)
    

    所以正确报错了:

    Traceback (most recent call last):
      File "valid.py", line 43, in <module>
        jsonschema.validate(data, specific_schema)
      File "/home/david/.pyenv/versions/3.7.11/lib/python3.7/site-packages/jsonschema/validators.py", line 934, in validate
        raise error
    jsonschema.exceptions.ValidationError: 'baritem' is a required property
    
    Failed validating 'required' in schema:
        {'additionalProperties': False,
         'properties': {'baritem': {'type': 'string'},
                        'key': {'enum': ['bar'], 'type': 'string'}},
         'required': ['key', 'baritem'],
         'type': 'object'}
    
    On instance:
        {'key': 'bar'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-16
      • 2017-07-26
      • 2017-05-02
      • 2011-11-06
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多