Reputation: 15394
I would like to access the index of an element in a jsonb array, like this:
SELECT
jsonb_array_elements(data->'Steps') AS Step,
INDEX_OF_STEP
FROM my_process
I don't see any function in the manual for this. Is this somehow possible?
Upvotes: 1
Views: 2606
Reputation: 121524
Use with ordinality.
You have to call the function in the from
clause to do this:
with my_process(data) as (
values
('{"Steps": ["first", "second"]}'::jsonb)
)
select value as step, ordinality- 1 as index
from my_process
cross join jsonb_array_elements(data->'Steps') with ordinality
step | index
----------+-------
"first" | 0
"second" | 1
(2 rows)
Read in the documentation (7.2.1.4. Table Functions):
If the WITH ORDINALITY clause is specified, an additional column of type bigint will be added to the function result columns. This column numbers the rows of the function result set, starting from 1.
Upvotes: 2
Reputation: 2685
You could try using
jsonb_each_text(jsonb)
which should supply both the key and value.
There is an example in this question: Extract key, value from json objects in Postgres except you would use the jsonb version.
Upvotes: 1