Wednesday, 15 September 2021

Pydantic: parse_file: get model from file content

‘parse_file’ is a class method that takes a file path, reads the file and passes the contents to parse_raw. If content_type is omitted, it is inferred from the file's extension.

 

Example

path = Path('parseFile.json')
path.write_text('{"id": 1, "name": "Krishna", "age": 32}')
emp1 = Employee.parse_file(path)

 

parse_file.py

from pydantic import BaseModel
from pathlib import Path

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

path = Path('parseFile.json')
path.write_text('{"id": 1, "name": "Krishna", "age": 32}')
emp1 = Employee.parse_file(path)
emp1Json = emp1.json()
print(emp1Json)

 

Output

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

 


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment