如何从JSON对象创建Python类?
我们可以使用建立在jsonschema基础之上的python-jsonschema-objects。python-jsonschema-objects为使用Python绑定JSON模式提供了基于类的自动绑定。
我们有一个示例的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
builder = pjs.ObjectBuilder(schema)
ns = builder.build_classes()
Person = ns.ExampleSchema
jack = Person(firstName="Jack", lastName="Sparrow")
jack.lastName
example_schema lastName=Sparrow age=None firstName=Jack
验证 –
jack.age = -2 python_jsonschema_objects.validators.ValidationError: -2 was less or equal to than 0
阅读更多:Python 教程
极客教程