简体   繁体   中英

SQLalchemy +Postgresql accessing Array of jsonb elements

I have a query that looks like this. query = db.query(status_cte.c.finding_status_history) the finding_status_history column is of type array when I check its .type . It's an array of jsonb objects I can easily change it to be json instead if it's easier. I've also tested this out with it as json .

[
    {
        "data": [
            {
                "status": "closed",
                "created_at": "2023-01-27T18:05:27.579817",
                "previous_status": "open"
            },
            {
                "status": "open",
                "created_at": "2023-01-27T18:05:28.694352",
                "previous_status": "closed"
            }
        ]
    },
    ...
]

I'm trying to access the first dictionary nested inside data and access the status column.

I've tried to grab it using query = db.query(status_cte.c.finding_status_history[0]) but this returns a list of empty dictionaries like so.

[
    {},
    {},
    {},
    {},
    {},
    {},
    {}
]

I'm not sure why that doesn't work as its my impression that i should grab the first entry. I'm assuming i need to access "data" some how first but i've also tried...

query = db.query(status_cte.c.finding_status_history.op('->>')('data') Which gives me jsonb[] ->> unknown operator doesn't exist . I've tried to type cast data to be that of String and i get the same error but jsonb[] ->> String etc etc

Also when looping through the items for item in query.all() i'm seeing that [0] results in (None,) and [1] results in

({
                "status": "closed",
                "created_at": "2023-01-27T18:05:27.579817",
                "previous_status": "open"
},)

as a tuple...

The secret was that [0] is not the first element. [1] is also noted that [-1] doesn't appear to give me the last element so i also had to order my aggregated json objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM