如何从JSON对象创建Python类?
我们可以使用在jsonschema之上构建的python-jsonschema-objects.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 pjsbuilder = 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
以上是 如何从JSON对象创建Python类? 的全部内容, 来源链接: utcz.com/z/353461.html