示例數據:
create table activity (data json);
insert into activity values
('{"avatar":"first.jpg","name":"first name"}'),
('{"avatar":"second.jpg","name":"second name"}'),
('{"avatar":"third.jpg","name":"third name"}');
在的Postgres 9.4你應該創建一個輔助功能:
create or replace function add_path_to_avatar(json)
returns json language sql as $$
select json_object_agg(key, value)
from (
select
key,
case key::text when 'avatar' then
'images/profiles/uploads/' || value
else value
end
from json_each_text($1)
) s
$$;
update activity
set data = add_path_to_avatar(data)
returning data;
data
-----------------------------------------------------------------------------
{ "avatar" : "images/profiles/uploads/first.jpg", "name" : "first name" }
{ "avatar" : "images/profiles/uploads/second.jpg", "name" : "second name" }
{ "avatar" : "images/profiles/uploads/third.jpg", "name" : "third name" }
(3 rows)
在的Postgres 9.5可以使用功能jsonb_set()
:
update activity
set data = jsonb_set(
data::jsonb,
'{avatar}',
format('"images/profiles/uploads/%s"', data#>>'{avatar}')::jsonb);
Postgres版本? – klin
PostgreSQL 9.4.5 – Shanthi