如何从 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 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
广告