使 jsonSchema enum 属性有条件地需要有用的错误消息

make jsonSchema enum attribute conditionally required with useful error message

我可能做错了,因为错误消息没有帮助 - 尽管 "works"

我有一个可以是 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

的错误

我是不是用错了?

如果您使用的是 >= 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'}