10 Python JSON Schema Validation Examples Using jsonschema Library
The article provides ten code examples demonstrating how to validate JSON data with Python's jsonschema library, covering basic validation, required fields, nested schemas, arrays, uniqueness, enums, ranges, pattern matching, conditional logic, and custom error messages.
JSON Schema是一种用于描述JSON数据结构的规范,它可以帮助开发者定义数据的形状和规则,从而确保数据符合预期的格式。Python的jsonschema库提供了强大的工具来验证JSON数据是否符合预定义的Schema。以下是10个使用jsonschema库进行数据验证的Python代码示例,旨在帮助你理解和应用JSON Schema验证。
示例1:基本的JSON Schema验证
import jsonschema
from jsonschema import validate
# JSON数据
data = {"name": "John Doe", "age": 30}
# JSON Schema
schema = {"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}}
# 验证
validate(instance=data, schema=schema)
print("Validation passed.")输出示例:
Validation passed.示例2:使用required关键字
import jsonschema
data = {"name": "John Doe"}
schema = {"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}, "required": ["name", "age"]}
try:
validate(instance=data, schema=schema)
except jsonschema.exceptions.ValidationError as e:
print(e)输出示例:
'age' is a required property示例3:模式嵌套
import jsonschema
data = {"user": {"name": "Jane Doe", "age": 25}}
schema = {"type": "object", "properties": {"user": {"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}}}}}
validate(instance=data, schema=schema)
print("Validation passed.")输出示例:
Validation passed.示例4:数组元素类型检查
import jsonschema
data = {"hobbies": ["reading", "swimming"]}
schema = {"type": "object", "properties": {"hobbies": {"type": "array", "items": {"type": "string"}}}}
validate(instance=data, schema=schema)
print("Validation passed.")输出示例:
Validation passed.示例5:数组中的唯一性检查
import jsonschema
data = {"hobbies": ["reading", "swimming", "reading"]}
schema = {"type": "object", "properties": {"hobbies": {"type": "array", "items": {"type": "string"}, "uniqueItems": True}}}
try:
validate(instance=data, schema=schema)
except jsonschema.exceptions.ValidationError as e:
print(e)输出示例:
['reading', 'swimming', 'reading'] has non-unique elements示例6:模式的枚举
import jsonschema
data = "apple"
schema = {"enum": ["apple", "banana", "cherry"]}
validate(instance=data, schema=schema)
print("Validation passed.")输出示例:
Validation passed.示例7:模式的最小最大值
import jsonschema
data = 10
schema = {"type": "integer", "minimum": 5, "maximum": 15}
validate(instance=data, schema=schema)
print("Validation passed.")输出示例:
Validation passed.示例8:模式的模式匹配
import jsonschema
data = "abc123"
schema = {"type": "string", "pattern": "^[a-z]+[0-9]+$"}
validate(instance=data, schema=schema)
print("Validation passed.")输出示例:
Validation passed.示例9:复合条件
import jsonschema
data = {"age": 18, "country": "US"}
schema = {"type": "object", "properties": {"age": {"type": "integer"}, "country": {"type": "string"}}, "if": {"properties": {"country": {"const": "US"}}}, "then": {"required": ["age"]}}
validate(instance=data, schema=schema)
print("Validation passed.")输出示例:
Validation passed.示例10:自定义错误消息
import jsonschema
data = {"age": 18}
schema = {"type": "object", "properties": {"age": {"type": "integer"}, "country": {"type": "string"}}, "required": ["country"], "error_required": {"country": "Country is required"}}
try:
validate(instance=data, schema=schema)
except jsonschema.exceptions.ValidationError as e:
print(e.message)输出示例:
Country is required这些示例展示了如何使用jsonschema库来验证JSON数据是否符合特定的模式。通过定义清晰的Schema,你可以确保数据的一致性和完整性,这对于任何需要处理结构化数据的应用程序来说都是至关重要的。
在使用jsonschema进行数据验证时,务必理解Schema的每个关键字的作用,以及它们如何组合在一起形成更复杂的验证逻辑。这将有助于你构建健壮和灵活的数据验证策略。
如果你有任何问题或需要进一步的帮助,欢迎随时留言。祝你验证愉快!
以上代码示例假设你的环境中已经安装了jsonschema库。如果尚未安装,可以使用pip进行安装:
pip install jsonschemaTest Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.