校驗json返回數據格式是否正確需要用到jsonschema
首先進行安裝
pip install jsonschema
示例
from jsonschema import validate result = { "code" : 0, "name": "中國", "msg": "login success!", "password": "000038efc7edc7438d781b0775eeaa009cb64865", "username": "test" } #校驗數據格式設定 schema = { "$schema": "http://json-schema.org/draft-04/schema#", "title": "test demo", "description": "validate result information", "type": "object", "properties": { "code": { "description": "error code", "type": "integer" }, "name": { "description": "name", "type": "string" }, "msg": { "description": "msg", "type": "string" }, "password": { "description": "error password", "maxLength": 20, "pattern": "^[a-f0-9]{20}$", # 正則校驗a-f0-9的16進制,總長度20 "type": "string" } }, "required": [ "code","name", "msg", "password" ] } # validate校驗, 跟assert斷言一個意思 validate(instance=result, schema=schema)
輸出為
因為password長度超過了我們校驗中限制的最大長度20