Currently I have a table my_table
with columns (id,product_id,text) and transform data into a json object like so:
SELECT
json_agg(
json_build_object(
'id', t.id,
'parent_id', t.product_id,
'text', t.text
)
)
FROM my_table AS t
Now that I am adding more columns to my_table
, I need to return a JSON object per each row from the selected list of rows from this table. Basically, talbe columns will be (id,product_id,text1,text2,text3)
And I want to return 3 identical objects with 1 different value of text (for text1,text2,text3)
How can I achieve this?
Use unnest()
to yield a single row as three ones:
select id, product_id, unnest(array[text1, text2, text3]) as text
from my_table
Create the json array from the above query:
select
json_agg (
json_build_object(
'id', id,
'product_id', product_id,
'text', text
)
)
from (
select id, product_id, unnest(array[text1, text2, text3]) as text
from my_table
) t
or
select
json_agg (
json_build_object(
'id', id,
'product_id', product_id,
'text', text
)
)
from my_table
cross join unnest(array[text1, text2, text3]) as text
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.