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. This is effectively a standalone version of [SchemaSerializer.to_json][pydantic_core.SchemaSerializer.to_json].
Parameters
| Name | Type | Description |
|---|---|---|
| value | Any | The Python object to serialize. |
| indent | `int | None` = None |
| ensure_ascii | bool = False | If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is. |
| include | `_IncEx | None` = None |
| exclude | `_IncEx | None` = None |
| by_alias | bool = True | Whether to use the alias names of fields. |
| exclude_none | bool = False | Whether to exclude fields that have a value of None. |
| round_trip | bool = False | Whether to enable serialization and validation round-trip support. |
| timedelta_mode | Literal['iso8601', 'float'] = 'iso8601' | How to serialize timedelta objects, either 'iso8601' or 'float'. |
| temporal_mode | Literal['iso8601', 'seconds', 'milliseconds'] = 'iso8601' | How to serialize datetime-like objects (datetime, date, time), either 'iso8601', 'seconds', or 'milliseconds'. iso8601 returns an ISO 8601 string; seconds returns the Unix timestamp in seconds as a float; milliseconds returns the Unix timestamp in milliseconds as a float. |
| bytes_mode | Literal['utf8', 'base64', 'hex'] = 'utf8' | How to serialize bytes objects, either 'utf8', 'base64', or 'hex'. |
| inf_nan_mode | Literal['null', 'constants', 'strings'] = 'constants' | How to serialize Infinity, -Infinity and NaN values, either 'null', 'constants', or 'strings'. |
| serialize_unknown | bool = False | Attempt to serialize unknown types, str(value) will be used, if that fails "< Unserializable {value_type} object >" will be used. |
| fallback | `Callable[[Any], Any] | None` = None |
| serialize_as_any | bool = False | Whether to serialize fields with duck-typing serialization behavior. |
| polymorphic_serialization | `bool | None` = None |
| context | `Any | None` = None |
Returns
| Type | Description |
|---|---|
bytes | JSON bytes. |