0

对于我的项目,我需要一个用于 json 模式的新属性。我将它命名为“isPropertyOf”,基本上我想要的是,如果我有这个:

fruits = {
    "banana": "yellow fruit",
    "apple": "round fruit"
}

schema = {
    "type": "object",
    "properties": {
        "fav_fruit": {
            "type": "string",
            "isPropertyOf": fruits
        }
    }
}

然后 schema 将仅验证{"fav_fruit":"banana"}or之类的对象{"fav_fruit":"apple"},但不验证{"fav_fruit":"salami"} (我知道对于这个例子来说,使用枚举会更有意义,但假设“fruits”也用于其他东西,我宁愿避免冗余)

我阅读了有关此的文档,并认为我需要使用jsonschema.validators.extend. 我尝试过这样的事情:

def is_property_of_callable(validator_instance, property_value, instance, schema):
    keys = [k for k in property_value]
    return instance in keys

mapping = {"isPropertyOf": is_property_of_callable}
my_validator = jsonschema.validators.extend(jsonschema.Draft7Validator, mapping)
instance = {"fav_fruit": "tobacco"}
my_validator(schema).is_valid(instance)

我已经准备好看到出现问题了,但显然验证器没有发现任何问题。我尝试了一个明显错误的实例,即使是 jsonschema 的标准验证器也不会接受

my_validator(schema).is_valid({"fav_fruit": 0})

但显然它看起来没问题。我想也许我添加这个属性的方式很糟糕,以至于它让验证器接受任何东西,所以我尝试了一个最小的验证器扩展案例:

minimal_validator = jsonschema.validators.extend(jsonschema.Draft7Validator, {})
minimal_validator(schema).is_valid(instance)

这个也很高兴 0 是我最喜欢的水果。

我在这里做错了什么?我怎样才能使它工作?

4

0 回答 0