skip to content

In Pydantic 2, how do model_dump(), model_dump(mode='json') and model_dump_json() differ, and when would you use each?

level: juniorimportance: must knowfreq 74%

answer

  1. two serializer modes
  2. dict versus string
  3. datetime and Decimal survive or not
  4. JSON-safe values without encoding

basics

~10 s

In Pydantic 2, model_dump() returns a dict that keeps Python values such as datetime, Decimal and tuples; model_dump(mode='json') returns a dict of JSON-safe values; model_dump_json() returns the encoded JSON string itself.

solid answer

~40 s

All three run the same serializer that Pydantic 2 builds from the model's type hints, in one of two modes. `model_dump()` uses Python mode: nested models become dicts, but a `datetime` stays a `datetime`, a `Decimal` stays a `Decimal` and a tuple stays a tuple. `model_dump(mode='json')` uses JSON mode and still returns a `dict`, only now every value is JSON-compatible: ISO 8601 strings for dates, a string for `Decimal`, lists for tuples and sets. `model_dump_json()` is JSON mode plus the encoding step, returning a compact `str`. I use `model_dump()` when the data stays in Python, `mode='json'` when another library does the encoding but needs safe values, and `model_dump_json()` when I need the payload for the wire. Version 1 called the first and last `.dict()` and `.json()`.

code

python · 28 lines
python
from datetime import datetime
from decimal import Decimal

from pydantic import BaseModel


class ShipmentDispatched(BaseModel):
    shipment_id: str
    dispatched_at: datetime
    weight_kg: Decimal
    parcel_ids: tuple[str, ...]


evt = ShipmentDispatched(
    shipment_id='s-41',
    dispatched_at=datetime(2026, 3, 1, 9, 30),
    weight_kg=Decimal('1.25'),
    parcel_ids=('p-1', 'p-2'),
)

print(evt.model_dump())
#> {'shipment_id': 's-41', 'dispatched_at': datetime.datetime(2026, 3, 1, 9, 30), 'weight_kg': Decimal('1.25'), 'parcel_ids': ('p-1', 'p-2')}

print(evt.model_dump(mode='json'))
#> {'shipment_id': 's-41', 'dispatched_at': '2026-03-01T09:30:00', 'weight_kg': '1.25', 'parcel_ids': ['p-1', 'p-2']}

print(evt.model_dump_json())
#> {"shipment_id":"s-41","dispatched_at":"2026-03-01T09:30:00","weight_kg":"1.25","parcel_ids":["p-1","p-2"]}

go deeper

for a junior

Recall the return types: a dict from model_dump(), a dict of JSON-safe values with mode='json', a string from model_dump_json(). Be ready to show what happens to a datetime in each.

for a middle

Explain that one serializer runs in Python or JSON mode, list the conversions JSON mode makes (dates, Decimal, tuples, bytes), and name the shared options such as exclude_none and by_alias.

for a senior

Show you know where dumps fail in production: PydanticSerializationError on an unencodable value, warnings on a mismatched assigned value, and config such as ser_json_inf_nan or ser_json_bytes changing what consumers receive.

for a principal

Frame the choice as a boundary decision: one agreed dump call per outbound payload, so every producer emits identical JSON, rather than each team re-encoding Python-mode dicts with its own encoder.

## Two output modes, one serializer Pydantic 2 builds a **serializer** for every model from its type hints, in the same way it builds a validator. The serializer runs in one of two **modes**, and the three calls in the question are just different ways of choosing a mode and a return type: - **Python mode** is what `model_dump()` does by default (`mode='python'`). The model becomes a `dict`, recursively, so nested models become nested dicts. Leaf values keep their Python types: a `datetime` stays a `datetime`, a `Decimal` stays a `Decimal`, a `tuple` stays a `tuple`. - **JSON mode** converts each value into something JSON can represent. `model_dump(mode='json')` returns a `dict` of those JSON-safe values. `model_dump_json()` goes one step further and returns the encoded `str`, without building an intermediate dict for you to encode again. Pydantic's own documentation uses the words "dump" and "serialize" interchangeably for all of this, so do not read anything into the choice of verb. ## What JSON mode changes | Field type | `model_dump()` | `model_dump(mode='json')` and `model_dump_json()` | |---|---|---| | `datetime`, `date` | the `datetime` or `date` object | an ISO 8601 string such as `'2026-03-01T09:30:00'` | | `Decimal` | `Decimal('1.25')` | the string `'1.25'` | | `tuple`, `set` | the tuple or set | a list (a JSON array) | | `UUID` | the `UUID` object | its string form | | `bytes` | the bytes | a string, UTF-8 by default | | nested model | a nested `dict` | a nested `dict` (a JSON object) | Some of these conversions are configurable in `model_config`: - `ser_json_bytes` chooses `'utf8'` (the default), `'base64'` or `'hex'` for bytes. - `ser_json_temporal`, added in 2.12 and now recommended over the older `ser_json_timedelta`, chooses ISO 8601 text or a number of seconds or milliseconds for date and time types. - `ser_json_inf_nan` decides how infinity and NaN floats are written; the default `'null'` writes them as `null`. ## Choosing between them 1. **`model_dump()`** when the result stays in Python: you pass it to code that wants real `datetime` and `Decimal` objects, merge it with another dict, or hand it to a driver that understands those types. 2. **`model_dump(mode='json')`** when something else will do the encoding but needs JSON-safe values first: a message client that calls `json.dumps` itself, a template, a cache that stores dicts. Calling `json.dumps(m.model_dump())` on a model with a `datetime` fails, because the standard `json` module cannot encode one; `mode='json'` is the fix. 3. **`model_dump_json()`** when you need the payload on the wire: publishing an event, writing a file, logging a record. The encoding happens inside Pydantic's core, and the output is compact, with no spaces after separators. ## Options the methods share Both methods accept the same shaping options: - `include` and `exclude`, as sets of field names or nested dicts for nested models and list items; - `by_alias`, which switches keys to the fields' serialization aliases; - `exclude_unset`, `exclude_defaults` and `exclude_none`, which drop fields by how they were set or by value; - `context`, which passes data through to custom serializers; - `round_trip`, `warnings`, `fallback`, `serialize_as_any` and `polymorphic_serialization` for the edge cases. `model_dump_json()` adds `indent` (compact output when omitted) and `ensure_ascii` (default `False`, so non-ASCII characters are written as they are). It has no `mode` argument, because it is always JSON. For a type that is not a model, `TypeAdapter.dump_python()` and `TypeAdapter.dump_json()` play the same two roles. ## Errors and look-alikes - In JSON mode, a value Pydantic does not know how to encode, typically an arbitrary class allowed with `arbitrary_types_allowed`, raises `PydanticSerializationError`. The `fallback` argument lets you supply a function for such values. - A field that holds a value not matching its type, for example one assigned after construction without `validate_assignment`, is still serialized, and Pydantic warns rather than raises by default; `warnings='error'` turns that into a `PydanticSerializationError`. - `dict(model)` is not a dump. Iterating a model yields `(field_name, value)` pairs as they are, so nested models stay model instances and nothing is converted. - In JSON mode, non-string dict keys are generally written with `str(key)`. ## Where the names come from Pydantic 1 called these methods `.dict()` and `.json()`. Version 2 renamed them `model_dump()` and `model_dump_json()`, keeps the old names only as deprecated shims, and added the `mode='json'` option, so a version 1 habit of `json.loads(m.json())` to get JSON-safe values becomes a single `m.model_dump(mode='json')`.

  • Why does json.dumps(m.model_dump()) fail on a model with a datetime field, and what is the smallest fix?
    `model_dump()` runs in Python mode, so the `datetime` object is left in the dict and the standard `json` module has no encoder for it, raising `TypeError`. Either ask Pydantic for JSON-safe values with `m.model_dump(mode='json')`, which turns the datetime into an ISO 8601 string, or skip the second encoder entirely with `m.model_dump_json()`.
  • How do you serialize a plain list of models, or a dict that is not a model, the same way?
    Wrap the type in a `TypeAdapter`, for example `TypeAdapter(list[ShipmentDispatched])`. Its `dump_python()` mirrors `model_dump()`, including `mode='json'`, and its `dump_json()` mirrors `model_dump_json()` but returns bytes. The same shaping options, such as `exclude_none` and `by_alias`, apply.
  • What happens when a model field holds a type Pydantic cannot encode as JSON?
    In JSON mode Pydantic raises `PydanticSerializationError`, often only when that object first reaches a dump, which is why it can slip into production. You can teach it the type with a custom serializer on the field, or pass a `fallback` function to the dump call to convert unknown values.

  • model_dump() already returns JSON-ready values, so json.dumps on it always works
  • model_dump(mode='json') returns a JSON string, the same as model_dump_json()
  • dict(model) is the same as model_dump() and converts nested models
  • model_dump_json() pretty-prints by default
  • The Pydantic 2 way to get JSON is still .json(), with .dict() for a dictionary

Assumes Pydantic 2; version 1 spelled these .dict() and .json(), which remain only as deprecated shims, and had no mode='json' option.