当前位置: 首页 > news >正文

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 是一个用来定义和校验 JSONweb 规范,简而言之,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 <= <= max

exclusiveMinimumexclusiveMaximum:指定数值必须严格大于或小于某个值(不包含等于)。

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.总结

http://www.dtcms.com/a/323553.html

相关文章:

  • Java类和对象课上练习题目设计
  • LLM 的向量的方向表示语义,向量长度表示什么
  • Docker容器lnmp平台部署discuz论坛
  • 工具类-高效集合差异计算工具DiffWrapper
  • visual studio 无明显错误,但是无法编译成功解决—仙盟创梦IDE
  • C++入门自学Day7-- String类的自实现
  • Adapting Vision-Language Models Without Labels A Comprehensive Survey
  • RWKV与VRWKV
  • Filter,Interceptor拦截器-登录校验
  • visual studio 字体设置
  • 【小米比笔记本Pro15.6】>>Stasrt PXE over IPv6,Press [Esc] to EXIT...
  • 第二十天:余数相同问题
  • 信息安全简要
  • 分布式锁详解及 Spring Boot 实战示例
  • Redis 持久化策略深度剖析:从原理到实战,守护数据不丢失
  • 基于 InfluxDB 的服务器性能监控系统实战(二)
  • [论文阅读] 人工智能 + 软件工程 | Posterior-GRPO:优化代码生成推理过程的新框架
  • Solana上Launchpad混战:新颖性应被重视
  • 云服务器--阿里云OSS(1)【阿里云OSS简单介绍以及环境准备】
  • 论文学习21:Pyramid Scene Parsing Network
  • AG32cpld实现一个UartTx“外设”
  • 莫比乌斯反演学习笔记
  • Qt 元对象系统中的 QMetaObject 类和他的invokeMethod() 函数及其他常见函数应用详解​
  • MoVA:多模态视觉专家混合架构的创新设计与应用实践
  • 【能碳建设2】把“能碳计算”做成可配置、可演示的系统
  • codeforces 补题1
  • FAN5622SX 四通道六通道电流吸收线性LED驱动器,单线数字接口 数字式调光, 2.7 → 5.5 V 直流直流输入, 30mA输出FAN5622S
  • 现代数据加密技术:守护数字世界的无形之盾
  • 供应链需求预测项目如何设定合理的KPI、准确率指标(十四)
  • jxWebUI--输入框