我正在尝试创建迁移并将列类型从varchar []更改为JSON。我希望以下列格式获得JSON
["US", "UK", "GER"] -> { "US": [], "UK": [], "GER": []}
现有表格:
CREATE TABLE countries (id SERIAL PRIMARY KEY NOT NULL, destinations VARCHAR [] NOT NULL)
INSERT INTO countries(destinations) VALUES('{"US","UK"}');
INSERT INTO countries(destinations) VALUES('{"GER","UA"}');
答案 0 :(得分:0)
您应该删除目的地,并将这些元素用作json_object_agg()
中的键。使用'[]'::json
作为空的json数组:
select id, json_object_agg(elem, '[]'::json)
from countries,
lateral unnest(destinations) elem
group by id;
id | json_object_agg
----+---------------------------
1 | { "US" : [], "UK" : [] }
2 | { "GER" : [], "UA" : [] }
(2 rows)