Pydantic's include parameter, passed to Pydantic models to set the
fields to include.
TYPE:Optional[IncEx]DEFAULT:None
exclude
Pydantic's exclude parameter, passed to Pydantic models to set the
fields to exclude.
TYPE:Optional[IncEx]DEFAULT:None
by_alias
Pydantic's by_alias parameter, passed to Pydantic models to define if
the output should use the alias names (when provided) or the Python
attribute names. In an API, if you set an alias, it's probably because you
want to use it in the result, so you probably want to leave this set to
True.
TYPE:boolDEFAULT:True
exclude_unset
Pydantic's exclude_unset parameter, passed to Pydantic models to define
if it should exclude from the output the fields that were not explicitly
set (and that only had their default values).
TYPE:boolDEFAULT:False
exclude_defaults
Pydantic's exclude_defaults parameter, passed to Pydantic models to define
if it should exclude from the output the fields that had the same default
value, even when they were explicitly set.
TYPE:boolDEFAULT:False
exclude_none
Pydantic's exclude_none parameter, passed to Pydantic models to define
if it should exclude from the output any fields that have a None value.
TYPE:boolDEFAULT:False
custom_encoder
Pydantic's custom_encoder parameter, passed to Pydantic models to define
a custom encoder.
Exclude from the output any fields that start with the name _sa.
This is mainly a hack for compatibility with SQLAlchemy objects, they
store internal SQLAlchemy-specific state in attributes named with _sa,
and those objects can't (and shouldn't be) serialized to JSON.
defjsonable_encoder(obj:Annotated[Any,Doc(""" The input object to convert to JSON. """),],include:Annotated[Optional[IncEx],Doc(""" Pydantic's `include` parameter, passed to Pydantic models to set the fields to include. """),]=None,exclude:Annotated[Optional[IncEx],Doc(""" Pydantic's `exclude` parameter, passed to Pydantic models to set the fields to exclude. """),]=None,by_alias:Annotated[bool,Doc(""" Pydantic's `by_alias` parameter, passed to Pydantic models to define if the output should use the alias names (when provided) or the Python attribute names. In an API, if you set an alias, it's probably because you want to use it in the result, so you probably want to leave this set to `True`. """),]=True,exclude_unset:Annotated[bool,Doc(""" Pydantic's `exclude_unset` parameter, passed to Pydantic models to define if it should exclude from the output the fields that were not explicitly set (and that only had their default values). """),]=False,exclude_defaults:Annotated[bool,Doc(""" Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define if it should exclude from the output the fields that had the same default value, even when they were explicitly set. """),]=False,exclude_none:Annotated[bool,Doc(""" Pydantic's `exclude_none` parameter, passed to Pydantic models to define if it should exclude from the output any fields that have a `None` value. """),]=False,custom_encoder:Annotated[Optional[Dict[Any,Callable[[Any],Any]]],Doc(""" Pydantic's `custom_encoder` parameter, passed to Pydantic models to define a custom encoder. """),]=None,sqlalchemy_safe:Annotated[bool,Doc(""" Exclude from the output any fields that start with the name `_sa`. This is mainly a hack for compatibility with SQLAlchemy objects, they store internal SQLAlchemy-specific state in attributes named with `_sa`, and those objects can't (and shouldn't be) serialized to JSON. """),]=True,)->Any:""" Convert any object to something that can be encoded in JSON. This is used internally by FastAPI to make sure anything you return can be encoded as JSON before it is sent to the client. You can also use it yourself, for example to convert objects before saving them in a database that supports only JSON. Read more about it in the [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/). """custom_encoder=custom_encoderor{}ifcustom_encoder:iftype(obj)incustom_encoder:returncustom_encoder[type(obj)](obj)else:forencoder_type,encoder_instanceincustom_encoder.items():ifisinstance(obj,encoder_type):returnencoder_instance(obj)ifincludeisnotNoneandnotisinstance(include,(set,dict)):include=set(include)ifexcludeisnotNoneandnotisinstance(exclude,(set,dict)):exclude=set(exclude)ifisinstance(obj,BaseModel):# TODO: remove when deprecating Pydantic v1encoders:Dict[Any,Any]={}ifnotPYDANTIC_V2:encoders=getattr(obj.__config__,"json_encoders",{})# type: ignore[attr-defined]ifcustom_encoder:encoders.update(custom_encoder)obj_dict=_model_dump(obj,mode="json",include=include,exclude=exclude,by_alias=by_alias,exclude_unset=exclude_unset,exclude_none=exclude_none,exclude_defaults=exclude_defaults,)if"__root__"inobj_dict:obj_dict=obj_dict["__root__"]returnjsonable_encoder(obj_dict,exclude_none=exclude_none,exclude_defaults=exclude_defaults,# TODO: remove when deprecating Pydantic v1custom_encoder=encoders,sqlalchemy_safe=sqlalchemy_safe,)ifdataclasses.is_dataclass(obj):obj_dict=dataclasses.asdict(obj)returnjsonable_encoder(obj_dict,include=include,exclude=exclude,by_alias=by_alias,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,custom_encoder=custom_encoder,sqlalchemy_safe=sqlalchemy_safe,)ifisinstance(obj,Enum):returnobj.valueifisinstance(obj,PurePath):returnstr(obj)ifisinstance(obj,(str,int,float,type(None))):returnobjifisinstance(obj,UndefinedType):returnNoneifisinstance(obj,dict):encoded_dict={}allowed_keys=set(obj.keys())ifincludeisnotNone:allowed_keys&=set(include)ifexcludeisnotNone:allowed_keys-=set(exclude)forkey,valueinobj.items():if((notsqlalchemy_safeor(notisinstance(key,str))or(notkey.startswith("_sa")))and(valueisnotNoneornotexclude_none)andkeyinallowed_keys):encoded_key=jsonable_encoder(key,by_alias=by_alias,exclude_unset=exclude_unset,exclude_none=exclude_none,custom_encoder=custom_encoder,sqlalchemy_safe=sqlalchemy_safe,)encoded_value=jsonable_encoder(value,by_alias=by_alias,exclude_unset=exclude_unset,exclude_none=exclude_none,custom_encoder=custom_encoder,sqlalchemy_safe=sqlalchemy_safe,)encoded_dict[encoded_key]=encoded_valuereturnencoded_dictifisinstance(obj,(list,set,frozenset,GeneratorType,tuple,deque)):encoded_list=[]foriteminobj:encoded_list.append(jsonable_encoder(item,include=include,exclude=exclude,by_alias=by_alias,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,custom_encoder=custom_encoder,sqlalchemy_safe=sqlalchemy_safe,))returnencoded_listiftype(obj)inENCODERS_BY_TYPE:returnENCODERS_BY_TYPE[type(obj)](obj)forencoder,classes_tupleinencoders_by_class_tuples.items():ifisinstance(obj,classes_tuple):returnencoder(obj)try:data=dict(obj)exceptExceptionase:errors:List[Exception]=[]errors.append(e)try:data=vars(obj)exceptExceptionase:errors.append(e)raiseValueError(errors)fromereturnjsonable_encoder(data,include=include,exclude=exclude,by_alias=by_alias,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,custom_encoder=custom_encoder,sqlalchemy_safe=sqlalchemy_safe,)