自 2018 年起,此库已弃用,请考虑改用 jsonschema。
概述
validictory 是一个通用的 Python 数据验证器,它允许验证任意 Python 数据结构。
Schema 格式基于JSON Schema 提议,因此与json库结合也可用作 JSON 数据的验证器。
包含来自Ian Lewis 和 Ysuke Muraoka的jsonschema的代码。
示例使用
JSON 文档和模式必须首先加载到 Python 字典类型中,然后才能对其进行验证。
解析一个简单的 JSON 文档:
>>> import validictory
>>> validictory.validate("roast beef", {"type":"string"})
解析更复杂的 JSON 文档:
>>> import json
>>> import validictory
>>> data = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
>>> schema = {
... "type":"array",
... "items":[
... {"type":"string"},
... {"type":"object",
... "properties":{
... "bar":{
... "items":[
... {"type":"string"},
... {"type":"any"},
... {"type":"number"},
... {"type":"integer"}
... ]
... }
... }
... }
... ]
... }
>>> validictory.validate(data,schema)
捕获 ValueErrors 来处理验证问题:
>>> import validictory
>>> try:
... validictory.validate("short", {"type":"string","minLength":15})
... except ValueError, error:
... print error
...
Length of value 'short' for field '_data' must be greater than or equal to 15
模式选项
type种类:
验证数据中的项目是否属于特定类型。如果提供了值列表,则将接受任何指定的类型。提供的值可以是以下任意组合:
- string- str 和 unicode 对象
- integer- 整数
- number- 整数和浮点
- boolean- 布尔值
- object- 字典
- array- 列表和元组
- null- 没有任何
- any- 任何类型都可以接受
properties:
properties
对象属性的验证器列表。
本质上,为属性提供的字典中的每个项目
都是应用于数据中具有相同名称的属性(如果存在)的子模式。
# each key in the 'properties' option matches a key in the object that you are validating,
# and the value to each key in the 'properties' option is the schema to validate
# the value of the key in the JSON you are verifying.
data = json.loads(''' {"obj1": {"obj2": 12}}''' )
schema =
{
"type": "object",
"properties": {
"obj1": {
"type": "object",
"properties": {
"obj2": {
"type": "integer"
}
}
}
}
}
validictory.validate(data, schema)