jsonb 字段中的 PostgreSQL 重命名属性
PostgreSQL rename attribute in jsonb field
在 postgresql 9.5 中,有没有办法重命名 jsonb 字段中的属性?
例如:
{ "nme" : "test" }
应重命名为
{ "name" : "test"}
在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)
我使用以下方法处理嵌套属性并跳过任何不使用旧名称的 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';
仅供参考文档:
#-
删除指定路径的字段或元素(对于JSON数组,负整数从末尾开始计算)
https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE
#>
获取指定路径下的JSON对象https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE
在 postgresql 9.5 中,有没有办法重命名 jsonb 字段中的属性?
例如:
{ "nme" : "test" }
应重命名为
{ "name" : "test"}
在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)
我使用以下方法处理嵌套属性并跳过任何不使用旧名称的 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';
仅供参考文档:
#-
删除指定路径的字段或元素(对于JSON数组,负整数从末尾开始计算) https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE#>
获取指定路径下的JSON对象https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE