python-jsonschema-objects 是术士的替代品,建立在 jsonschema 之上
python-jsonschema-objects 提供基于类的自动绑定到 JSON 模式以在 python 中使用。
用法:
示例 Json 架构
schema = '''{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
},
"dogs": {
"type": "array",
"items": {"type": "string"},
"maxItems": 4
},
"gender": {
"type": "string",
"enum": ["male", "female"]
},
"deceased": {
"enum": ["yes", "no", 1, 0, "true", "false"]
}
},
"required": ["firstName", "lastName"]
} '''
将模式对象转换为类
import python_jsonschema_objects as pjs
import json
schema = json.loads(schema)
builder = pjs.ObjectBuilder(schema)
ns = builder.build_classes()
Person = ns.ExampleSchema
james = Person(firstName="James", lastName="Bond")
james.lastName
u'Bond' james
example_schema lastName=Bond age=None firstName=James
验证:
james.age = -2
python_jsonschema_objects.validators.ValidationError: -2 少
或等于 0
但问题是,它仍在使用 draft4validation,而 jsonschema 已移至 draft4validation,我在 repo 上提交了一个关于此的 issue。
除非您使用的是旧版本的 jsonschema ,否则上述包将如图所示。