Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is correct mapped annotation for `JSON` in SQLAlchemy 2.x version?

The new version of SQLAlchemy introduced the ability to use type annotations using Mapped[Type] (link).

My question is, what should we use as an annotation for sqlalchemy.types.JSON? Is just dict will be ok?

I'm just using dict, but I want to understand the correct option for this.

like image 656
May Flower Avatar asked Aug 31 '25 20:08

May Flower


1 Answers

You will need to first declare a mapping in your DeclarativeBase Type Annotation Map like this:

from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.types import JSON
from typing import Any


class Base(DeclarativeBase):
    type_annotation_map = {
        dict[str, Any]: JSON
    }

See the docs on type_annotation_map for more information.

Note: This will also work for database specific json dialects, eg Postgres' JSONB type. For older versions of Python, you may need to do from typing import Dict and use that instead of using dict directly.

After doing so, you can use the above datatype in your table as so:

from sqlalchemy.orm import Mapped

class YourTable(Base):
    your_column: Mapped[dict[str, Any]]
like image 165
Gamrix Avatar answered Sep 03 '25 19:09

Gamrix