数据库中的每条记录都有一个json列表,我试图从中返回每个元素内的值。
我要退货
environmental services, energy & utilities
来自
[
{
"key": "environmental services"
},
{
"key": "energy & utilities"
}
]
然后。
construction
来自
[
{
"key": "construction"
}
]
每个记录中每个json列表的长度不确定的地方。
我可以通过以下方式获得第一个值:
select
column_name -> 0 -> 'key'
from table
但是如何获得全部。
如何在postgresql中做到这一点?
答案 0 :(得分:1)
在横向联接中使用函数jsonb_array_elements()
来获取数组的所有元素和聚合函数string_agg()
:
with my_table(json_col) as (
values
('[
{
"key": "environmental services"
},
{
"key": "energy & utilities"
}
]'::jsonb),
('[
{
"key": "construction"
}
]')
)
select string_agg(value->>'key', ', ')
from my_table
cross join jsonb_array_elements(json_col)
group by json_col -- use PK here (if exists)
string_agg
--------------------------------------------
environmental services, energy & utilities
construction
(2 rows)