首页 > 解决方案 > 使用有用的错误消息有条件地要求 jsonSchema 枚举属性

问题描述

我可能做错了,因为错误消息没有帮助-即使这“有效”

我有一个可以是 aaa 或 bbb 的枚举 (field1)

如果它是 aaa,那么 field2 必须是必需的。如果不是 aaa,则 field2 可以是可选的

我现在有这个

"anyOf": [
    {
        "properties": {
            "field1": {
                "const": "aaa"
            }
        },
        "required": [
            "field2"
        ]
    },
    {
        "properties": {
            "field1": {
                "const": "bbb"
            }
        }
    }
]

但如果 field1 = aaa 并且未指定 field2,这是我得到的错误:

E           jsonschema.exceptions.ValidationError: 'bbb' was expected
E           
E           Failed validating 'const' in schema[1]['properties']['field1']:
E               {'const': 'bbb'}
E           
E           On instance['httpMethod']:
E               'aaa'

我期待一个错误更像"field2" expected because schema[1]['properties']['field1'] == bbb

我用错了吗?

标签: pythonjsonschema

解决方案


如果您使用 >= draft-07,我想if-then(-else)会给您最好的错误。

from jsonschema import Draft7Validator

schema = {
    "type": "object",
    "properties": {
        "field1": {
            "enum": [
                "aaa",
                "bbb"
            ]
        },
        "field2": {
            "type": "string"
        }
    },
    "if": {
        "properties": { "field1": { "const": "aaa" } }
    },
    "then": {
        "required": [ "field2" ]
    }
}

obj = {
    "field1": "aaa",
}

Draft7Validator(schema).validate(obj)

它将产生错误:

Traceback (most recent call last):
  File "error.py", line 28, in <module>
    Draft7Validator(schema).validate(obj)
  File "(...)/jsonschema/validators.py", line 353, in validate
    raise error
jsonschema.exceptions.ValidationError: 'field2' is a required property

Failed validating 'required' in schema['if']['then']:
    {'required': ['field2']}

On instance:
    {'field1': 'aaa'}

推荐阅读