to_json
Serialize a Python object to JSON including transforming and filtering data.
def to_json(
value: Any,
indent: int | None = None,
ensure_ascii: bool = False,
include: _IncEx | None = None,
exclude: _IncEx | None = None,
by_alias: bool = True,
exclude_none: bool = False,
round_trip: bool = False,
timedelta_mode: Literal['iso8601', 'float'] = 'iso8601',
temporal_mode: Literal['iso8601', 'seconds', 'milliseconds'] = 'iso8601',
bytes_mode: Literal['utf8', 'base64', 'hex'] = 'utf8',
inf_nan_mode: Literal['null', 'constants', 'strings'] = 'constants',
serialize_unknown: bool = False,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
polymorphic_serialization: bool | None = None,
context: Any | None = None
) - > bytes
Serialize a Python object to JSON including transforming and filtering data.
Parameters
| Name | Type | Description |
|---|---|---|
| value | Any | The Python object to serialize. |
| indent | `int | None` = None |
| ensure_ascii | bool = False | If True, all non-ASCII characters in the output are escaped; otherwise, they are output as-is. |
| include | `_IncEx | None` = None |
| exclude | `_IncEx | None` = None |
| by_alias | bool = True | Whether to use the defined alias names for fields instead of the Python attribute names. |
| exclude_none | bool = False | Whether to exclude fields that have a value of None from the serialized output. |
| round_trip | bool = False | Whether to enable serialization and validation round-trip support. |
| timedelta_mode | Literal['iso8601', 'float'] = 'iso8601' | Determines how timedelta objects are serialized, either as ISO 8601 strings or float values. |
| temporal_mode | Literal['iso8601', 'seconds', 'milliseconds'] = 'iso8601' | Determines how datetime, date, and time objects are serialized (ISO 8601 string, or Unix timestamp in seconds/milliseconds). |
| bytes_mode | Literal['utf8', 'base64', 'hex'] = 'utf8' | Determines the encoding format for bytes objects. |
| inf_nan_mode | Literal['null', 'constants', 'strings'] = 'constants' | Determines how Infinity and NaN values are represented in the JSON output. |
| serialize_unknown | bool = False | Whether to attempt serializing unknown types using their string representation. |
| fallback | `Callable[[Any], Any] | None` = None |
| serialize_as_any | bool = False | Whether to use duck-typing serialization behavior for fields. |
| polymorphic_serialization | `bool | None` = None |
| context | `Any | None` = None |
Returns
| Type | Description |
|---|---|
bytes | The serialized JSON data as a bytes object. |