基于jsonschema的json验证程序包,它为最终用户返回更好的验证错误
json_payload_validator的Python项目详细描述
格式化来自jsonschema的验证错误消息的小python包。 如果您希望独立的json验证器与任何框架分离,那么应该使用这个包。
原因
jsonschema确实很酷,但它的验证错误消息很糟糕,因为它们是为开发人员而不是最终用户准备的。 因此,如果您有一个使用jsonschema验证json有效负载并希望向 您可以使用此软件包的最终用户:)
工作原理
3个简单的规则:
- 如果在有效负载中不发送必需的属性,则会收到消息'foo' is a required property。
- 如果验证失败,则将返回验证规则Validation of property 'foo' failed: {'minLength': 2, 'type': 'string', 'maxLength': 50}。
- 如果在验证规则中添加message属性,则将返回其值而不是规则Validation of property 'foo' failed: Custom error message。
用法
pip install json_payload_validator
成功的验证示例
fromjson_payload_validatorimportvalidateschema={'type':'object','properties':{'name':{'type':'string','minLength':2,'maxLength':50},},'required':['name']}payload={'name':'John Maus'}error=validate(payload,schema)print(error)# None
必需的属性示例
fromjson_payload_validatorimportvalidateschema={'type':'object','properties':{'name':{'type':'string'},},'required':['name']}payload={}error=validate(payload,schema)print(error)# 'name' is a required property
验证规则失败示例
fromjson_payload_validatorimportvalidateschema={'type':'object','properties':{'name':{'type':'string',{'minLength':2,'type':'string','maxLength':50}},},'required':['name']}payload={'name':555}error=validate(payload,schema)print(error)# Validation of property 'name' failed: {'minLength': 2, 'type': 'string', 'maxLength': 50}
自定义错误消息示例
fromjson_payload_validatorimportvalidateschema={'type':'object','properties':{'name':{'type':'string','message':'Name must be a string'},},'required':['name']}payload={'name':555}error=validate(payload,schema)print(error)# Validation of property 'name' failed: Name must be a string