'How to JSONIFY a dict having a pydantic model

I am new to pydantic and am stuck. Below code is throwing error TypeError: Type is not JSON serializable: Person

from pydantic import BaseModel,Extra
from typing import Mapping, Optional, Any,List
from orjson import dumps

class Address(BaseModel):
    place: str

class Person(BaseModel):
    name: str
    age: int
    address: Mapping[str, str]={}
    class Config:
        anystr_strip_whitespace: True
        extra: Extra.allow
        allow_population_by_field_name: True

person={'name':'tom','age':12,"gender":"male"}
person=Person(**person)
person.address['place']='XYZ'
dict={'class':'X','person':person}

dumps(dict)

Any idea how to get this working ?



Solution 1:[1]

You need to use the Pydantic method .dict() to convert the model to a Python dictionary.

IMPORTANT you are assigning your dictionary to the Python dict type! Use a different variable name other than 'dict', like below I made it 'data_dict'.

Here is your solution:

from pydantic import BaseModel,Extra
from typing import Mapping, Optional, Any,List
from orjson import dumps

class Address(BaseModel):
    place: str

class Person(BaseModel):
    name: str
    age: int
    address: Mapping[str, str]={}
    class Config:
        anystr_strip_whitespace: True
        extra: Extra.allow
        allow_population_by_field_name: True

person={'name':'tom','age':12,"gender":"male"}
person=Person(**person)
person.address['place']='XYZ'
data_dict={'class':'X','person':person.dict()}

dumps(data_dict)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zaffer