new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

Pydantic · all subjects

serialization & output

9 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Serialize Pydantic model to JSON string for Redis queue

Use the model_dump_json() method to serialize a Pydantic model instance to a JSON string for pushing to a Redis queue. This returns a JSON string representation of the model that can be stored in Redis.

Deserialize and validate JSON from Redis queue

Use the model_validate_json() class method to deserialize and validate JSON data retrieved from a Redis queue. This method accepts JSON bytes or string data and returns a validated model instance.

User.model_validate with JSON response

The User.model_validate() method can validate JSON response data from HTTP requests. It takes the parsed JSON object and returns a validated model instance. For example: user = User.model_validate(response.json()) validates JSON from an httpx response.

Serialization of nested model subclasses changed

In Pydantic V2, when serializing a model with nested fields, only fields defined on the annotated type are included, unlike V1 which included all subclass fields. This helps prevent accidental security bugs.

JSON method deprecated in V2

The `.json()` method is deprecated in Pydantic V2. Use `model_dump_json()` instead. Attempting to use deprecated `.json()` with arguments such as `indent` or `ensure_ascii` may lead to confusing errors.

JSON serialization of dict keys with None changed

In Pydantic V2, JSON serialization of non-string key values uses `str(key)`. For example, None keys in dicts are serialized as 'None' instead of 'null'. In V1, they were serialized as 'null'.

model_dump_json output is compacted

In Pydantic V2, `model_dump_json()` results are compacted without spaces to save space, and don't always exactly match `json.dumps()` output. To align them, use `json.dumps(model.model_dump(), separators=(',', ':'))`.

Input types not preserved in V2 collections

In Pydantic V2, input types are not preserved for generic collections. The output type will match the type annotation (typically a plain dict for Mapping), but the input type (e.g., collection.Counter) is not preserved. Use TypeAdapter or custom validators if preservation is needed.

Subclass types are preserved for BaseModel and dataclasses

In Pydantic V2, while input types are generally not preserved for standard types, they are preserved for subclasses of BaseModel and dataclasses.

Give your agent this brain