简体   繁体   中英

Postgres: How to copy elements from text array column into a json column?

I have a text array column and now I would like to create a new JSON column. In JSON column I would like to create key-value pairs from text array and current time stamp.

Example:

Text array {"aa", "bb", "cc"} -> JSON {"aa":"12:00", "bb":"12:00", "cc":"12:00"}

How do I update this way all rows in the whole table?

Assuming the current column is named data and the new column is new_data you can do something like this:

update the_table
  set new_data = x.new_data
from (
  select id, jsonb_object_agg(t.k, to_char(now(), 'hh24:mi')) as new_data
  from the_table, unnest(data) as t(k)
  group by id
) x
where x.id = foo.id;

Online example: https://rextester.com/SMBH72985

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM