Jsonshcema——一个验证json数据格式的工具。
官网link:https://python-jsonschema.readthedocs.io/en/latest/
understanding json shcema : https://json-schema.org/understanding-json-schema/about.html
先看一个官网例子,感受一下。
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"price": {"type": "number"},
"name": {"type": "string"},
},
}
# 根据给出的模版验证给出的示例, 如果验证失败会raise erro
'''
if cls is None:
cls = validator_for(schema)
cls.check_schema(schema)
validator = cls(schema, *args, **kwargs)
error = exceptions.best_match(validator.iter_errors(instance))
if error is not None:
raise error
'''
print(validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema))
It’s just a declarative format for “describing the structure of other data”--用以描述其他数据格式的声明。
shceme中的类型按照JavaScript编写,下图是javascript和python类型的映射关系。
{ "type": "number" }
{ "type": ["number", "string"] } 可以接收多个类型
In Python, "string" is analogous to the unicode
type on Python 2.x, and the str
type on Python 3.x.
length
{
"type": "string",
"maxLength":2,
"minLength":3
}
正则表达式
{
"type": "string",
"pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
}
format
format关键字允许对常用的某些类型的字符串值进行基本的语义验证。比如:日期,邮箱,ip等。
interger Multiples
{"type":"integer"} 42 OK 42.0 erroe
{ "type": "number", "multipleOf": 1.0 } 42 ok 42.0 ok
number Multiples
# 使用multipleOf关键字可以将数字限制为给定数字的倍数。
# 只能是10的倍数
{
"type" : "number",
"multipleOf" : 10
}
Range
与python有一点的区别是key只能是字符串
properties
{
"type": "object",
"properties": {
"number": { "type": "number" },
"street_name": { "type": "string" },
"street_type": { "type": "string",
"enum": ["Street", "Avenue", "Boulevard"]
}
}
}
可以缺省属性,以及增加另外的k-v。但是additionalProperties的指为false时,不能增加k-v;如果值为object{"type":"string"},那么增加的属性只能是字符串。
Required properties
如果有一些字段必须填写,可以使用该属性进行限制。
{
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string" },
"address": { "type": "string" },
"telephone": { "type": "string" }
},
"required": ["name", "email"]
}
more:https://json-schema.org/understanding-json-schema/reference/object.html
items
list validation
{
"type": "array",
"items": {
"type": "number"
}
}
所有元素必须都是数字 或者为[]
{
"type": "array",
"contains": {
"type": "number"
}
}
元素中包含数字
tuple valiadation
uniqueness
length