如何从 JSON 对象创建 Python 类?
pythonserver side programmingprogrammingjson
我们可以使用基于 jsonschema 构建的 python-jsonschema-objects。python-jsonschema-objects 提供基于类的自动绑定到 JSON 模式以供在 Python 中使用。
我们有一个示例 json 模式,如下所示
schema = '''{ "title": "Example Schema", "type": "object", "properties": { "firstName": { "typequot;: "stringquot; }, "lastNamequot;: { "typequot;: "stringquot; }, "agequot;: { "descriptionquot;: "年龄(岁)quot;, &"类型":"整数", &"最小值":0 }, &"狗":{ &"类型":"数组", &"项目":{"类型":"字符串"}, &"maxItems":4 }, &"性别":{ &"类型":"字符串", &"枚举":["男性","女性"] }, "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