jsonschema
先安裝 jsonschema 依賴包
pip install jsonschema
jsonschema 用於定義 JSON 數據結構以及校驗 JSON 數據內容。支持python2.7以上+jsonschema
參考文檔地址:https://python-jsonschema.readthedocs.io/en/latest/
完全支持 Draft 7, Draft 6, Draft 4 和 Draft 3
項目實戰
如下帶有token的校驗,由於token的值不固定,它是一個30位長度的16進制,0-9和a-f生成的字符串,可以用正則匹配
from jsonschema import validate
# 需要校驗的內容
result = {
"code": 0,
"msg": "login success!",
"token": "000038efc7edc7438d781b0775eeaa009cb64865",
"username": "test"
}
# 編寫schema 內容
#下面是給json定義一個規范,也就是json中每個key的value值的數據類型,長度或使用正則校驗起始或結尾的字符等
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"
},
"msg": {
"description": "error msg ",
"type": "string"
},
"token":
{
"description": "login success return token",
"maxLength": 30,#長度
"pattern": "^[a-f0-9]{40}$", # 正則校驗a-f0-9的16進制,總長度40
"type": "string"#類型
}
},
"required": [
"code", "msg", "token"
]
}
assert(instance=result, schema=schema)#result要校驗的數據,schema規范
validate 校驗成功時候,不會有報錯
JSON 數據校驗失敗,拋出 jsonschema.exceptions.ValidationError 異常
schema 模式本身有問題,拋出 jsonschema.exceptions.SchemaError 異常
schema語法
| 參數 | 描述 |
|---|---|
| $schema | 表示該JSON Schema文件遵循的規范 |
| title | 為該JSON Schema文件提供一個標題 |
| description | 關於該JSON Schema文件的描述信息 |
| type | 表示待校驗元素的類型(例如,最外層的type表示待校驗的是一個JSON對象,內層type分別表示待校驗的元素類型為,整數,字符串,數字) |
| properties | 定義待校驗的JSON對象中,各個key-value對中value的限制條件 |
| required | 定義待校驗的JSON對象中,必須存在的key |
| minimum | 用於約束取值范圍,表示取值范圍應該大於或等於minimum |
| exclusiveMinimum | 如果minimum和exclusiveMinimum同時存在,且exclusiveMinimum的值為true,則表示取值范圍只能大於minimum |
| maximum | 用於約束取值范圍,表示取值范圍應該小於或等於maximum |
| exclusiveMaximum | 如果maximum和exclusiveMaximum同時存在,且exclusiveMaximum的值為true,則表示取值范圍只能小於maximum |
| multipleOf | 用於約束取值,表示取值必須能夠被multipleOf所指定的值整除 |
| maxLength | 字符串類型數據的最大長度 |
| minLength | 字符串類型數據的最小長度 |
| pattern | 使用正則表達式約束字符串類型數據 |
type取值
| type取值 | python數據類型 |
|---|---|
| object | dict |
| array | list |
| integer | int |
| number | float或int |
| null | None |
| boolean | bool |
| string | str |
