jsonb字段中的PostgreSQL重命名属性

时间:2017-02-17 22:53:00

标签: json postgresql jsonb

在postgresql 9.5中,有没有办法在jsonb字段中重命名属性?

例如:

{ "nme" : "test" }

应重命名为

{ "name" : "test"}

3 个答案:

答案 0 :(得分:31)

UPDATE中使用delete (-) and concatenate (||) operators,例如:

create table example(id int primary key, js jsonb);
insert into example values
    (1, '{"nme": "test"}'),
    (2, '{"nme": "second test"}');

update example
set js = js - 'nme' || jsonb_build_object('name', js->'nme')
where js ? 'nme'
returning *;

 id |           js            
----+-------------------------
  1 | {"name": "test"}
  2 | {"name": "second test"}
(2 rows)

答案 1 :(得分:4)

我使用以下方法处理嵌套属性并跳过任何不使用旧名称的json:

UPDATE table_name
SET json_field_name = jsonb_set(json_field_name #- '{path,to,old_name}',
                                '{path,to,new_name}',
                                json_field_name#>'{path,to,old_name}')
WHERE json_field_name#>'{path,to}' ? 'old_name';

答案 2 :(得分:0)

我的变量类型是json。当我用jsonb更改它时,我做不到,因为它取决于查看。无论如何,我用column_name :: jsonb修复了它。 我想与遇到这种问题的人分享。 也谢谢@klin