Tuesday 14 September 2021

Pydantic: parse_raw: Convert string or bytes to a model object

‘parse_raw’ is a class method, and takes a str or bytes and parses it as json, then passes the result to parse_obj.

 

Example

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

 

parse_raw_demo.py

from pydantic import BaseModel

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

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

 

Output

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

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment