Thursday 9 September 2021

Pydantic: json(): serialize model to a json

Pydantic models has a json() method, it is used to serialize a model to json string.

 

Below table summarizes the arguments passed to json() method.

 

Argument

Description

include

fields to include in the returned json

exclude

fields to exclude from the returned json

by_alias

whether field aliases should be used as keys in the returned dictionary

exclude_unset

whether fields which were not set when creating the model and have their default values should be excluded from the returned dictionary; default False

exclude_defaults

whether fields which are equal to their default values (whether set or otherwise) should be excluded from the returned dictionary; default False

exclude_none

whether fields which are equal to None should be excluded from the returned dictionary

encoder

a custom encoder function passed to the default argument of json.dumps()

**dumps_kwargs

any other keyword arguments are passed to json.dumps()

 

Example

emp1 = Employee(id = 1, name = 'Ptr', age = 23, dateOfBirth = datetime(1988, 6, 6, 12, 13, 14))
emp1Json = emp1.json()

json_method_demo_1.py

from pydantic import BaseModel, ValidationError
from datetime import datetime

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

emp1 = Employee(id = 1, name = 'Ptr', age = 23, dateOfBirth = datetime(1988, 6, 6, 12, 13, 14))
emp1Json = emp1.json()

print('emp1Json -> ' + emp1Json)


Output

emp1Json -> {"id": 1, "name": "Ptr", "age": 23, "dateOfBirth": "1988-06-06T12:13:14"}


Previous                                                    Next                                                    Home

No comments:

Post a Comment