目錄
1.介紹
2.安裝
3.使用
3.1type關鍵字
3.2最大值最小值
3.2.1minimum 、?maximum
3.2.2 exclusiveMinimum?、exclusiveMaximum
3.3字符串特殊校驗
3.4數據約束
3.5對象約束
3.6必須屬性
3.7依賴關系
4.總結
?
1.介紹
JSON Schema 是一個用來定義和校驗 JSON 的 web 規范,簡而言之,JSON Schema 是用來校驗 json 是否符合預期。
根據 json 創建 JSON Schema 后,你可以使用你選擇的語言中的驗證器將示例數據與你的模式進行驗證。
在線JSON轉Schema工具 - ToolTT在線工具箱
2.安裝
pip install jsonschema==4.23.0
3.使用
3.1type關鍵字
type 關鍵字指定了數據類型,可用于驗證 JSON 數據中每個屬性的數據類型是否符合預期。常用的數據類型如下:
type | 解釋 |
---|---|
string | 字符串類型,用于文本數據。 |
number | 數字類型,用于表示浮點數。 |
integer | 整數類型,用于表示整數。 |
boolean | 布爾類型,值為 true 或 false。 |
object | 對象類型,用于嵌套的 JSON 對象。 |
array | 數組類型,用于列表或集合。 |
null | 空值類型。 |
properties 是一個驗證關鍵字。當你定義 properties 時,你創建了一個對象,其中每個屬性代表正在驗證的 JSON 數據中的一個鍵。
from jsonschema import validatedef test2():(字典結構,鍵值對形式)json={"name": "zhangsan","height": 175.55}(用于校驗json_data的結構)jsonschema = {"type": "object","properties": {"name": {"type": "string"},"height": {"type": "integer"}}}validate(json,jsonschema)
?
3.2最大值最小值
minimum 和 maximum:指定數值的最小值和最大值。
min <= x?<= max
exclusiveMinimum 和 exclusiveMaximum:指定數值必須嚴格大于或小于某個值(不包含等于)。
min < x < max
3.2.1minimum 、?maximum
from jsonschema import validatedef test2():json={"name": "zhangsan","age": 20}jsonschema = {"type": "object","properties": {"name": {"type": "string"},"age": {"type": "integer","minimum": 18,"maximum": 120}}}validate(instance=json,schema=jsonschema)
未成年報錯:
3.2.2 exclusiveMinimum?、exclusiveMaximum
from jsonschema import validatedef test2():json={"name": "zhangsan","age": 18}jsonschema = {"type": "object","properties": {"name": {"type": "string"},"age": {"type": "integer","exclusiveMinimum": 18,"exclusiveMaximum": 20}}}validate(instance=json,schema=jsonschema)
?
3.3字符串特殊校驗
pattern :使用正則表達式來驗證字符串是否符合特定的模式。
正則表達式 – 語法 | 菜鳥教程
?
from jsonschema import validatedef test2():json={"name": "zhangsan","age": 19}jsonschema = {"type": "object","properties": {"name": {"type": "string","pattern": r"\S{4,20}"},"age": {"type": "integer","exclusiveMinimum": 18,"exclusiveMaximum": 20}}}validate(instance=json,schema=jsonschema)
?
3.4數據約束
關鍵字 | 作用描述 |
---|---|
minItems | 指定數組最小長度 |
maxItems | 指定數組最大長度 |
uniqueItems | 確保數組元素唯一 |
items | 定義數組元素的類型與約束 |
?
from jsonschema import validatedef test3():json= {"data": [1,2,3,4,5,5],"string": "pytest"}jsonschema= {"type": "object","required": [],"properties": {"data": {"type": "array",#對數組添加最小長度和最大長度"minItems": 1,"maxItems": 6,"uniqueItems": True,"items": {"type": "number"}},"string": {"type": "string"}}}validate(instance=json, schema=jsonschema)
?
3.5對象約束
關鍵字 | 作用說明 |
---|---|
minProperties | 指定對象的最小屬性數量,即對象至少要有多少個屬性 |
maxProperties | 指定對象的最大屬性數量,即對象最多能有多少個屬性 |
additionalProperties | 控制對象是否允許存在未在 properties 中定義的額外屬性,默認值為 True |
JSON Schema 默認不會對對象其他屬性進行校驗
from jsonschema import validatedef test_01():# JSON數據(字典結構,鍵值對形式)json_data = {"code": "SUCCESS","errMsg": "","data": False,#其他鍵"title": "測試"}# JSON Schema(用于校驗json_data的結構)json_schema = {"type": "object","required": [], # 可指定必須包含的字段,如 ["code", "errMsg"]"properties": {"code": {"type": "string"},"errMsg": {"type": "string"},"data": {"type": "boolean"}}}validate(json_data, json_schema)
additionalProperties??
控制對象是否允許存在未在 properties 中定義的額外屬性,默認值為 True
from jsonschema import validatedef test_01():# JSON數據(字典結構,鍵值對形式)json_data = {"code": "SUCCESS","errMsg": "","data": False,#其他鍵"title": "測試"}# JSON Schema(用于校驗json_data的結構)json_schema = {"type": "object",#不允許有額外的字段"additionalProperties": False,"required": [], # 可指定必須包含的字段,如 ["code", "errMsg"]"properties": {"code": {"type": "string"},"errMsg": {"type": "string"},"data": {"type": "boolean"}}}validate(json_data, json_schema)
參數太多時,我們可以使用對應的網站:
在線JSON轉Schema工具 - ToolTT在線工具箱
但是要注意二次檢查,可能會出現錯誤。
嵌套的json對象:
?
def testblog_list():url="http://8.137.19.140:9090/blog/getList"hread = {"user_token_header":"eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlck5hbWUiOiJ6aGFuZ3NhbiIsImV4cCI6MTc1NDczNTA5M30.cva2orifFbPsqSUlY9HJedF2hvIaRbXkMKqMOJTMx7o"}response = requests.get(url=url, headers=hread)print(response.json())json_schema={"type": "object","required": [],#additionalProperties 在哪里就限制哪一層級"additionalProperties": False,"properties": {"code": {"type": "string"},"errMsg": {"type": "string"},"data": {"type": "array","items": {"type": "object","required": [],#additionalProperties 在哪里就限制哪一層級"additionalProperties": False,"properties": {"id": {"type": "number"},"title": {"type": "string"},"content": {"type": "string"},"userId": {"type": "number"},"deleteFlag": {"type": "string"},"createTime": {"type": "string"},"updateTime": {"type": "string"},"loginUser": {"type": "boolean"}}}}}}validate(json_schema, response.json())
minProperties、maxProperties
from jsonschema import validatedef test_01():# JSON數據(字典結構,鍵值對形式)json_data = {"code": "SUCCESS","errMsg": "","data": False,}# JSON Schema(用于校驗json_data的結構)json_schema = {"type": "object",#最少一個屬性,最多兩個屬性"minProperties": 1,"maxProperties": 2,#不允許有額外的字段"additionalProperties": False,"required": [], # 可指定必須包含的字段,如 ["code", "errMsg"]"properties": {"code": {"type": "string"},"errMsg": {"type": "string"},"data": {"type": "boolean"}}}validate(json_data, json_schema)
將屬性個數設置為3
3.6必須屬性
通過 required 關鍵字,JSON Schema 可以指定哪些屬性是必需的。如果 JSON 實例中缺少這些必需屬性,驗證將失敗(防止某些屬性沒有數據導致失敗)。
例:
from jsonschema import validatedef test_01():# JSON數據(字典結構,鍵值對形式)json_data = {}# JSON Schema(用于校驗json_data的結構)json_schema = {"type": "object","required": [], # 可指定必須包含的字段,如 ["code", "errMsg"]"properties": {"code": {"type": "string"},"errMsg": {"type": "string"},"data": {"type": "boolean"}}}validate(json_data, json_schema)
?
required ?缺少 data 屬性校驗
from jsonschema import validatedef test_01():# JSON數據(字典結構,鍵值對形式)json_data = {"code": "SUCCESS","errMsg": "",}# JSON Schema(用于校驗json_data的結構)json_schema = {"type": "object","required": ["code","errMsg","data"], # 可指定必須包含的字段,如 ["code", "errMsg"]"properties": {"code": {"type": "string"},"errMsg": {"type": "string"},"data": {"type": "boolean"}}}validate(json_data, json_schema)
3.7依賴關系
dependentRequired 可以定義屬性之間的依賴關系。
- 當 JSON 實例里有 creditCard 屬性時,必須同時包含 billingAddress 屬性,不然驗證不通過;
- 要是沒有 creditCard 屬性,billingAddress 存在或不存在都可以 。
代碼格式:
{"type": "object","properties": {"creditCard": {"type": "string"},"billingAddress": {"type": "string"}},"dependentRequired": {"creditCard": ["billingAddress"]}
}
示例:
缺少密碼
def test04():json = {"username": "zhangsan",# "password": "123456","age": 18,"height": 175.8}jsonschema = {"type": "object","required": [],"properties": {"username": {"type": "string"},"password": {"type": "string"},"age": {"type": "number"},"height": {"type": "number"}},"dependentRequired": {"username": ["password"]}}validate(instance=json, schema=jsonschema)
缺少賬號:
兩者都沒有:
4.總結
?