Thư viện python-jsonschema-objects (xây dựng trên jsonschema) cung cấp liên kết tự động dựa trên class cho JSON schema để sử dụng trong Python.
Ví dụ JSON Schema
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"]
}'''
Chuyển schema thành class
import python_jsonschema_objects as pjs builder = pjs.ObjectBuilder(schema) ns = builder.build_classes() Person = ns.ExampleSchema jack = Person(firstName="Jack", lastName="Sparrow") print(jack.lastName) # Sparrow
Validation tự động
jack.age = -2 # python_jsonschema_objects.validators.ValidationError: -2 was less or equal to than 0
Thư viện tự động validate dữ liệu dựa trên schema (kiểu dữ liệu, giá trị tối thiểu, enum, v.v.).