Python中如何验证数据是否符合JSON格式?求实现示例
使用jsonschema验证动态JSON格式的示例方法
首先安装依赖:
pip install jsonschema
因为你的JSON内容每次运行都会变化,核心思路是根据当前需要验证的规则,动态编写对应的JSON Schema——Schema就是你定义的格式约束,比如必填字段、数据类型、取值范围等。下面给几个不同场景的实用示例:
示例1:验证用户信息JSON
假设本次需要验证的JSON必须包含name(字符串,必填)、age(整数,≥18),可选字段email(符合邮箱格式):
from jsonschema import validate, ValidationError # 动态定义本次验证的Schema user_schema = { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer", "minimum": 18}, "email": {"type": "string", "format": "email"} }, "required": ["name", "age"] # 必填字段列表 } # 待验证的动态JSON数据 user_data = { "name": "Alice", "age": 22, "email": "alice@example.com" } # 执行验证 try: validate(instance=user_data, schema=user_schema) print("JSON格式符合要求") except ValidationError as e: print(f"验证失败:{e.message}")
示例2:验证数组类型的JSON
如果本次需要验证的是一个至少包含1个正整数的数组:
from jsonschema import validate, ValidationError array_schema = { "type": "array", "items": {"type": "integer", "minimum": 1}, "minItems": 1 # 数组最小元素数量 } array_data = [1, 3, 5] try: validate(instance=array_data, schema=array_schema) print("JSON格式符合要求") except ValidationError as e: print(f"验证失败:{e.message}")
关键注意点
- 每次运行程序时,可根据当前验证需求动态生成Schema(比如从配置文件读取、或根据用户输入的规则生成)
- 常见Schema约束包括:
type(数据类型)、required(必填字段)、minimum/maximum(数值范围)、format(预定义格式,如email、url)、pattern(正则匹配)等 - 捕获
ValidationError可精准定位不符合规则的位置,方便给用户反馈
内容的提问来源于stack exchange,提问作者Weeechi
相关产品推荐
相关产品推荐

