如何将值连接到postgres中json数据类型中的值

时间:2016-02-08 11:50:26

标签: json postgresql

json列“data”包含类似

的值

RegAllocBase

我想为所有json密钥头像连接reStructuredText

我试过

{"avatar":"kiran1454916822955.jpg","name":"shanthitwos charmlyi"}

1 个答案:

答案 0 :(得分:1)

示例数据:

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);