Jsonshcema——一个验证json数据格式的工具。
官网link:https://python-jsonschema.readthedocs.io/en/latest/
understanding json shcema : https://json-schema.org/understanding-json-schema/about.html
先看一个官网例子,感受一下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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)) |
什么是schema?
It’s just a declarative format for “describing the structure of other data”--用以描述其他数据格式的声明。
关键字类型
shceme中的类型按照JavaScript编写,下图是javascript和python类型的映射关系。

1 | { "type": "number" } |
1 | { "type": ["number", "string"] } 可以接收多个类型 |
String https://json-schema.org/understanding-json-schema/reference/string.html
In Python, "string" is analogous to the
length
1 2 3 4 5 | { "type": "string", "maxLength":2, "minLength":3 } |
正则表达式
1 2 3 4 | { "type": "string", "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$" } |
format
format关键字允许对常用的某些类型的字符串值进行基本的语义验证。比如:日期,邮箱,ip等。
正则表达 https://json-schema.org/understanding-json-schema/reference/regular_expressions.html
数字类型
interger Multiples
1 2 | {"type":"integer"} 42 OK 42.0 erroe { "type": "number", "multipleOf": 1.0 } 42 ok 42.0 ok |
number Multiples
1 2 3 4 5 6 | # 使用multipleOf关键字可以将数字限制为给定数字的倍数。 # 只能是10的倍数 { "type" : "number", "multipleOf" : 10 } |
Range

Object (python中dict)
与python有一点的区别是key只能是字符串
properties
1 2 3 4 5 6 7 8 9 10 | { ??????? "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
如果有一些字段必须填写,可以使用该属性进行限制。
1 2 3 4 5 6 7 8 9 10 | { "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
array (对应python中的list/tuple)
items
list validation
1 2 3 4 5 6 | { "type": "array", "items": { "type": "number" } } |
所有元素必须都是数字 或者为[]
1 2 3 4 5 6 | { "type": "array", "contains": { "type": "number" } } |
元素中包含数字
tuple valiadation
uniqueness
length
MORE : https://json-schema.org/understanding-json-schema/index.html