Tuesday, 14 September 2021

Pydantic: parse_obj(): Convert the dictionary to a model object

‘parse_obj()’ is a class method, and takes a dictionary as argument and return the model object.

 

Example

emp1 = Employee.parse_obj({'id' : 1, 'name' : 'Krishna', 'age': 32})

 

parse_obj_demo.py

from pydantic import BaseModel

class Employee(BaseModel):
    id: int
    name: str
    age: int

emp1 = Employee.parse_obj({'id' : 1, 'name' : 'Krishna', 'age': 32})
emp1Json = emp1.json()
print(emp1Json)

 

Output

{"id": 1, "name": "Krishna", "age": 32}

 

Note

If the object passed is not a dict a ValidationError will be raised.

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment