skip to content

In Pydantic 2, an event dumped with model_dump_json() fails or comes back different when read with model_validate_json(); what breaks the round trip, and how do you guard it?

level: seniorimportance: should knowfreq 36%

answer

  1. output rules differ from input rules
  2. alias on one side only
  3. extra keys meet extra='forbid'
  4. NaN, bytes, Json[T], subclasses
  5. a round-trip test per event

basics

~20 s

A Pydantic 2 dump need not validate back: input-only aliases, computed fields under extra='forbid', custom serializers, NaN written as null, bytes encodings, Json[T] and subclass fields all differ. Guard it with a round-trip test per published model.

solid answer

~40 s

A dump follows output rules and validation follows input rules, and several defaults differ. A field with `alias='parcelId'` dumps as `parcel_id` unless you dump by alias, and validation accepts only the alias, so reading back fails with `missing`. A `@computed_field` adds a key that `extra='forbid'` rejects with `extra_forbidden`. A plain serializer can write a shape the field's validator refuses. `ser_json_inf_nan` defaults to `'null'`, so NaN comes back as `null` and a `float` field rejects it. `ser_json_bytes` must match `val_json_bytes`. A `Json[T]` field dumps its parsed value unless `round_trip=True`. A subclass instance is dumped as its declared type, losing fields. Even a clean round trip marks every field as set. I guard it with a test that dumps each published model the way production does and asserts `Model.model_validate_json(payload) == original`.

code

python · 21 lines
python
from pydantic import BaseModel, Field, ValidationError


class ParcelShipped(BaseModel):
    parcel_id: str = Field(alias='parcelId')


evt = ParcelShipped(parcelId='p-9')
payload = evt.model_dump_json()
print(payload)
#> {"parcel_id":"p-9"}

try:
    ParcelShipped.model_validate_json(payload)
except ValidationError as exc:
    print(exc.errors()[0]['type'])
    #> missing

same = ParcelShipped.model_validate_json(evt.model_dump_json(by_alias=True))
print(same == evt)
#> True

go deeper

for a junior

Recall that a dump and validation are separate steps, and that an alias used for input is not used for output unless you dump by alias.

for a middle

Explain the common breakers: alias defaults, computed fields meeting extra='forbid', plain serializers, NaN written as null, and how model_validate_json treats JSON input.

for a senior

Diagnose a failed or lossy round trip from the error type, and guard published models with round-trip tests that use production dump options, including fields-set drift.

for a principal

Treat published payloads as contracts: one base class fixing alias and encoding settings, and round-trip tests in CI for every event model, so producers and consumers cannot drift.

## Why a dump is not automatically valid input Pydantic 2 compiles two separate pieces of logic from a model's type hints: a **validator** that decides what input it accepts, and a **serializer** that decides what a dump writes. They agree for plain fields, but a number of defaults and customisations exist on one side only. A **round trip** means dumping an instance, for example with `model_dump_json()`, and validating the result again, for example with `model_validate_json()`; you get either a `ValidationError` or an instance that differs from the original. ## The usual causes | Cause | What the dump writes | What validation does with it | |---|---|---| | `Field(alias='parcelId')` with default settings | `"parcel_id"`, because `by_alias` is off | expects `parcelId`, because `validate_by_name` defaults to `False`: error type `missing` | | `@computed_field` and `extra='forbid'` | an extra key such as `"weight_kg"` | `extra_forbidden`; with the default `extra='ignore'` it is silently dropped | | a plain `field_serializer` that formats a value | for example `"1.25 kg"` for a `float` | a parsing error, because the validator never learned that format | | a NaN or infinite `float` | `null`, since `ser_json_inf_nan` defaults to `'null'` | a `float` field rejects `null` | | `bytes` with mismatched config | text in the `ser_json_bytes` encoding | decoded with `val_json_bytes`; Pydantic's docs say to set the two equal | | a `Json[list[int]]` field | the parsed list, not the original string | a `Json` field expects a JSON string; `round_trip=True` writes the string back | | a subclass instance in a field typed as the base model | only the base model's fields | a base-model instance; the subclass's data is gone | The last row is deliberate: Pydantic serializes the declared type so that undeclared, possibly sensitive subclass fields stay out of output. When you need them, `polymorphic_serialization` (2.13) or the `SerializeAsAny` annotation serializes the runtime class instead. ## Subtler differences after a successful round trip - **`model_fields_set` changes.** A full dump writes every field, so the re-validated instance considers every field explicitly set. A later `model_dump(exclude_unset=True)` now includes values that were defaults in the original. Equality (`==`) does not compare the set, so tests will not notice. - **Types narrow or widen.** A `tuple` becomes a JSON array and is converted back to a tuple, which is fine, but a field typed `Any` or a union can come back as a different type than went in. - **Strict models.** JSON input is allowed to carry dates as strings and tuples as arrays even under `strict=True`, because Pydantic knows JSON has no such types; the same dict fed to `model_validate()` in strict mode would fail. Read JSON back with `model_validate_json()`, not `model_validate(json.loads(...))`. ## Reading the error type The `type` of each entry in `ValidationError.errors()` usually points straight at the cause: - `missing` on an aliased field: the dump used field names while validation expects aliases. - `extra_forbidden`: the dump wrote keys the model does not declare, usually computed fields. - `float_type` on a float field: the value arrived as `null`, typically a NaN or infinity written by the default `ser_json_inf_nan`. - `float_parsing` or `int_parsing`: a custom serializer wrote a formatted string the validator cannot parse. - No error but missing data: a subclass was dumped as its declared type. ## Guarding it 1. **Write a round-trip test for every published model.** Build representative instances, including edge values such as empty lists, `None`, non-ASCII text and boundary numbers, dump them with the exact options production uses, and assert `Model.model_validate_json(payload) == original`. 2. **Dump and read with one alias policy.** Set `serialize_by_alias=True` on a shared base class, or pass `by_alias=True` at the single publishing point, and the input side, which validates by alias by default, already agrees. 3. **Decide what computed fields mean to readers.** Pydantic's docstring suggests the dedicated `round_trip` dump option for dumps meant to be read back; `exclude_computed_fields=True` (2.12) is the explicit alternative. Otherwise keep `extra` relaxed on the reading model. 4. **Pair every output setting with its input twin:** `ser_json_bytes` with `val_json_bytes`, and choose `ser_json_inf_nan` deliberately if NaN can occur. 5. **Keep plain serializers reversible**, or give the field a matching before-mode validator, which is the validators' material. ## What to say in an interview The short form is: dumping and validating are two programs generated from one class, so test the composition rather than assuming it. Naming two or three concrete causes, aliases, computed fields and NaN, shows you have seen it fail.

  • The round trip succeeds and the instances compare equal, yet a later PATCH-style dump includes defaults it did not before. Why?
    A full dump writes every field, so the re-validated instance has every field in `model_fields_set`. Equality ignores that set, so the test passes, but `model_dump(exclude_unset=True)` now emits values that were defaults on the original instance. Keep the original instance, or dump with `exclude_unset=True` when the distinction must survive.
  • Why read JSON back with model_validate_json() rather than model_validate(json.loads(payload))?
    `model_validate_json()` knows the input is JSON, so even a strict model accepts an ISO string for a `date` and an array for a `tuple`, because JSON has no such types. Feeding the decoded dict to `model_validate()` validates as Python input, where a strict model rejects those same values.
  • How do you keep a subclass's extra fields in a nested dump on purpose?
    Pydantic 2 serializes a nested model as its declared type by default. Set `polymorphic_serialization=True` in the config of the base model the field is annotated with, or pass it to the dump call (both 2.13), or annotate the field with `SerializeAsAny[...]`. Do it knowingly: the default exists so undeclared fields such as secrets are not leaked.

  • Anything model_dump_json() writes, model_validate_json() will accept
  • Validation ignores computed fields in input whatever the extra setting
  • NaN floats are written as NaN by default, so they read back fine
  • A nested subclass instance is dumped with all of its own fields by default
  • Equal instances after a round trip means model_fields_set matches too