Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 Β· Serialization

Dumping to Dicts and JSON

Master Pydantic serialization: python and json modes, include and exclude (including nested fields), exclude_unset, exclude_none, indent, round trips and field-level exclude.

Validation brings data in; serialization sends it back out: to a response body, a file, a cache, a message queue. Pydantic can turn any model into a dictionary or a JSON string, and gives you fine control over what is included. This lesson goes deeper than the quick overview you saw in Model Methods.

Two outputs, two modes

model_dump() returns Python objects (mode="python", the default). Dates stay as date, enums stay as enum members, sets stay as sets. model_dump(mode="json") returns only JSON-compatible values (strings, numbers, lists, dicts), and model_dump_json() returns the final JSON text.

Python python mode vs json mode

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use python mode when the next step is more Python code (a database library, another function). Use json mode or model_dump_json() when the output leaves your program as text.

model_dump_json() is faster than json.dumps(model.model_dump(mode="json")) because it serializes straight to bytes in Rust, without building the intermediate dictionary.

include and exclude

Both take a set of field names, or a dictionary for nested fields. Using ... (Ellipsis) means "the whole sub-object".

Python Choosing fields

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For fields that should never be dumped, such as an internal flag or a password hash, declare it once with Field(exclude=True); no call has to remember to exclude it:

Python Field(exclude=True)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dropping unset, default and None values

Argument Removes
exclude_unset=True fields that were not provided when the model was created
exclude_defaults=True fields whose value equals their default
exclude_none=True fields whose value is None
Python Trimming output

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

exclude_unset is the key tool for PATCH requests (Optional Fields and Defaults). exclude_none is common when an external API rejects explicit null values.

Pretty and compact JSON

model_dump_json(indent=2) pretty-prints. By default the JSON is compact with no spaces. Non-ASCII characters are written as real characters, not \uXXXX escapes.

Python Formatting JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Round trips

A round trip serializes a model and validates the result back into an equal model. It is the basis of caching and message passing. It works out of the box for most types:

Python Dump and load again

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If the model contains a type whose JSON form loses information (say a bytes field holding non-UTF-8 data), pass round_trip=True to the dump so Pydantic uses a representation that can be read back faithfully.

Subclasses and serialize_as_any

By default Pydantic serializes a field using the declared type. If a field is annotated Animal but holds a Dog with an extra breed field, only Animal's fields are written. Pass serialize_as_any=True to the dump call to use the runtime type instead:

Python Declared type vs runtime type

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This design avoids leaking sub-class fields by accident (an Admin user inside a field typed User), which makes the safe behaviour the default.

Warnings for wrong types

If a field holds a value of an unexpected type, for example because you assigned to it without validate_assignment, model_dump emits a warning instead of failing silently. Treat those warnings as bugs and fix the data or turn on assignment validation.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. What is the difference between model_dump() and model_dump(mode='json')?

    mode='json' converts dates, enums, sets, UUIDs and so on to JSON-friendly values but still returns a dict.
  2. 2. Which argument drops fields that were not provided when the model was created?

    exclude_unset uses model_fields_set, so explicit values (even equal to the default) stay.
  3. 3. How do you make sure a password_hash field never appears in any dump?

    Field(exclude=True) is applied once, in the model, to all dumps.
  4. 4. A field is annotated Animal but holds a Dog. What does model_dump() include by default?

    Serialization follows the declared type unless you pass serialize_as_any=True.

Summary

  • model_dump() gives Python objects, model_dump(mode="json") gives JSON-compatible values, model_dump_json() gives JSON text (and is the fastest).
  • include/exclude accept sets and nested dicts; Field(exclude=True) removes a field from every dump.
  • exclude_unset, exclude_defaults and exclude_none trim the output.
  • Dump and re-validate is a safe round trip for typical models; use round_trip=True for lossy types.
  • Fields are serialized by their declared type; serialize_as_any=True uses the runtime type.

Next: Aliases and Naming Conventions