Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để tạo lớp Python từ đối tượng JSON?


Chúng ta có thể sử dụng python-jsonschema-objects được xây dựng trên jsonschema. python-jsonschema-objects cung cấp liên kết dựa trên lớp tự động với các lược đồ JSON để sử dụng trong Python.

Chúng tôi có một lược đồ json mẫu như sau

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 đổi đối tượng lược đồ thành lớp

 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 

Xác thực -

jack.age = -2 python_jsonschema_objects.validators.ValidationError: -2 was less or equal to than 0