Linux-JSON Schema
目录
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)
缺少账号:
两者都没有: