2
votes

I have a column x with data type jsonb

and the values looks like:

[
{"key": "6cd", "type": "text1", "label": "label_text_1", "content": "description"},
{"key": "815", "type": "text2", "label": "label_text_2", "content": "desc2"}
]

How to return an array of strings which contains all the elements with a Postgres query?

Something like this:

["6cd", "text1","label_text_1","description","815","text2","label_text_2","desc2"]

2

2 Answers

2
votes

Use jsonb_array_elements(json_column) to get array elements and jsonb_each_text(elem) to get values of all nested objects in these elements:

with my_table(id, json_column) as (
values(
    1, 
    '[
        {"key": "6cd", "type": "text1", "label": "label_text_1", "content": "description"},
        {"key": "815", "type": "text2", "label": "label_text_2", "content": "desc2"}
    ]'::jsonb)
)

select id, array_agg(val)
from my_table
cross join jsonb_array_elements(json_column) as a(elem)
cross join jsonb_each_text(elem) as e(key, val)
group by id

 id |                             array_agg                             
----+-------------------------------------------------------------------
  1 | {6cd,text1,label_text_1,description,815,text2,label_text_2,desc2}
(1 row) 
1
votes
select array_agg(value) from t
join lateral jsonb_array_elements(col) e(v)
on true 
join lateral jsonb_each_text(v)
on true