1

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 ?

Naxi
  • 1,504
  • 5
  • 33
  • 72
  • 2
    Convert person to dict `dict = {'class': 'X', 'person': person.dict()}`. More detailed here https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict – alex_noname Jul 07 '21 at 09:43

1 Answers1

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)
Zaffer
  • 1,290
  • 13
  • 32