pythonjsonschema删除额外的并使用默认值

2024-09-28 23:45:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是pythonjsonschemahttps://python-jsonschema.readthedocs.io/en/latest/ 我正在尝试如何使用默认值,并在找到时删除其他字段。在

有人知道我该怎么做吗? 或者有另一个解决方案来验证支持默认值的jsonschema并删除任何附加字段(比如jsavj)?在


Tags: ioreadthedocs解决方案latestenjsonschemajsavjpythonjsonschemahttps
1条回答
网友
1楼 · 发布于 2024-09-28 23:45:02

隐藏在FAQ中你会发现这个

Why doesn’t my schema’s default property set the default on my instance? The basic answer is that the specification does not require that default actually do anything.

For an inkling as to why it doesn’t actually do anything, consider that none of the other validators modify the instance either. More importantly, having default modify the instance can produce quite peculiar things. It’s perfectly valid (and perhaps even useful) to have a default that is not valid under the schema it lives in! So an instance modified by the default would pass validation the first time, but fail the second!

Still, filling in defaults is a thing that is useful. jsonschema allows you to define your own validator classes and callables, so you can easily create an jsonschema.IValidator that does do default setting. Here’s some code to get you started. (In this code, we add the default properties to each object before the properties are validated, so the default values themselves will need to be valid under the schema.)

from jsonschema import Draft4Validator, validators


def extend_with_default(validator_class):
    validate_properties = validator_class.VALIDATORS["properties"]

    def set_defaults(validator, properties, instance, schema):
        for property, subschema in properties.iteritems():
            if "default" in subschema:
                instance.setdefault(property, subschema["default"])

        for error in validate_properties(
            validator, properties, instance, schema,
        ):
            yield error

    return validators.extend(
        validator_class, {"properties" : set_defaults},
    )


DefaultValidatingDraft4Validator = extend_with_default(Draft4Validator)


# Example usage:
obj = {}
schema = {'properties': {'foo': {'default': 'bar'}}}
# Note jsonschem.validate(obj, schema, cls=DefaultValidatingDraft4Validator)
# will not work because the metaschema contains `default` directives.
DefaultValidatingDraft4Validator(schema).validate(obj)
assert obj == {'foo': 'bar'}

发件人:https://python-jsonschema.readthedocs.io/en/latest/faq/#why-doesn-t-my-schema-s-default-property-set-the-default-on-my-instance

相关问题 更多 >