I have a data like below
id | customer | region | circle
----------------------------------
1 | airtel | tn | c1
2 | reliance | ap | c2
I am expecting the json output like below using PostgreSQL
JSON
[
{"id":"1_airtel","parent":"#","text":"airtel"},
{"id":"1_airtel_tn","parent":"1_airtel","text":"tn"},
{"id":"1_airtel_tn_c1","parent":"1_airtel_tn","text":"c1"},
{"id":"2_reliance","parent":"#","text":"reliance"},
{"id":"2_reliance_ap","parent":"2_reliance","text":"ap"},
{"id":"2_reliance_ap_c2","parent":"2_reliance_ap","text":"c2"}
]
One option uses a lateral join to generate the rows, and then json function to_jsonb()
to turn them to object. The final step is aggregation:
select jsonb_agg(to_jsonb(v)) res
from mytable t
cross join lateral (values
(
concat_ws('_', id::text, customer),
'#',
customer
),
(
concat_ws('_', id::text, customer, region),
concat_ws('_', id::text, customer),
region
),
(
concat_ws('_', id::text, customer, region, circle),
concat_ws('_', id::text, customer, region),
circle
)
) v(id, parent, 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.