访问 jsonb 数组中元素的索引

Access the index of an element in a jsonb array

我想访问 jsonb 数组中元素的索引,如下所示:

SELECT
  jsonb_array_elements(data->'Steps') AS Step,
  INDEX_OF_STEP

FROM my_process

我在 manual 中没有看到任何功能。 这有可能吗?

您可以尝试使用

jsonb_each_text(jsonb)

应该同时提供键和值。

这题有个例子: 除了你会使用 jsonb 版本。

使用 with ordinality. 您必须调用 from 子句中的函数来执行此操作:

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)    

阅读文档 (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.