PostgreSQL – Select Item from JSONB Array as Top-Level JSON Object

jsonpostgresql

I have JSONB column which stores the data in this format

[
    {
        "item1": "value1",
        "item2": "value2"
    },
    {
        "item1": "value3",
        "item2": "value4"
    }
]

I am trying to select 'item1' with query

SELECT jsonb_array_elements(data)->'item1' FROM test_table

Error I am getting is:

cannot extract elements from an object

How should I change the query to make it work?

Best Answer

You need to unnest the array elements to rows in the from clause:

select i.dt -> 'item1' as item1
from test_table t
  cross join jsonb_array_elements(t.data) as i(dt)