JsonSchema中format的用法

当你实例化validator时,如果没有给它传format_checker参数, jsonschema是不会自动校验schema中的format关键字的.
因此,你需要做以下步骤:
先去官方文档中,找到你需要校验的格式的包名
https://python-jsonschema.readthedocs.io/en/latest/validate/
如图所示:

format对应包名

然后去下载它到你的环境里.
如果你的checker没有找到对应的包时,会默认为校验通过,并且不会抛出错误.因此一定要先确保你的环境中有对应的包.

下面以python为例,介绍两种简单的方法.
一.

from jsonschema._format import draft7_format_checker
from jsonschema.validators import Draft7Validator

formats = draft7_format_checker
validator = Draft7Validator(schema, format_checker=formats)
validator.is_valid(instance)

这种方法会对所有jsonschema中原生的format进行校验.

二.

import jsonschema
from jsonschema.validators import Draft7Validator

formats = jsonschema.FormatChecker(formats=["ipv4", "iri"])
validator = Draft7Validator(schema, format_checker=formats)
validator.is_valid(instance)

这种方法仅对传入的formats进行校验,其他全部忽略.

你可能感兴趣的:(JsonSchema中format的用法)