Skip to content

2.12.0: PydanticSerializationError when using serialize_as_any #12348

@carl-baillargeon

Description

@carl-baillargeon

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Hello,

We are hitting a serialization error on Pydantic 2.12 on our RootModel implementation. Here's a snippet of the traceback:

  File "/home/carl/git_projects/anta/anta/catalog.py", line 263, in to_json
    return self.model_dump_json(serialize_as_any=True, exclude_unset=True, indent=2)
           ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/carl/git_projects/.dev/lib/python3.13/site-packages/pydantic/main.py", line 528, in model_dump_json
    return self.__pydantic_serializer__.to_json(
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        self,
        ^^^^^
    ...<13 lines>...
        serialize_as_any=serialize_as_any,
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ).decode()
    ^
pydantic_core._pydantic_core.PydanticSerializationError: Error serializing to JSON: PydanticSerializationError: Unable to serialize unknown type: <class 'module'>

Serialization works fine on Pydantic 2.11.10.

Example Code

from types import ModuleType

from pydantic import BaseModel


class Model(BaseModel, arbitrary_types_allowed=True):
    m: ModuleType


import os

m = Model(m=os)

m.model_dump_json(serialize_as_any=True)
#> pydantic_core._pydantic_core.PydanticSerializationError: Unable to serialize unknown type: <class 'module'>

Python, Pydantic & OS Version

(.dev) ~/git_projects/stuff/avd (main ✗) python -c "import pydantic.version; print(pydantic.version.version_info())"
             pydantic version: 2.12.0
        pydantic-core version: 2.41.1
          pydantic-core build: profile=release pgo=false
               python version: 3.13.3 (main, Apr  9 2025, 04:03:52) [Clang 20.1.0 ]
                     platform: Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.36
             related packages: pydantic-extra-types-2.10.5 pydantic-settings-2.11.0 typing_extensions-4.15.0 mypy-1.18.2
                       commit: unknown

Sub-issues

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V2Bug related to Pydantic V2

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions