How I can create Python class from JSON object?

PythonServer Side ProgrammingProgrammingJSON

We can use python-jsonschema-objects which is built on top of jsonschema.The python-jsonschema-objects provide an automatic class-based binding to JSON schemas for use in Python.

We have a sample json schema as follows

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"] } '''

Converting the schema object to class

 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 

Validation −

jack.age = -2 python_jsonschema_objects.validators.ValidationError: -2 was less or equal to than 0
raja
Published on 29-Jan-2018 10:23:31
Advertisements