在postgresql 9.5中,是否有一种方法可以重命名jsonb字段中的属性?
例如:
例如:
{ "nme" : "test" }
应该被重新命名为
{ "name" : "test"}
{ "nme" : "test" }
应该被重新命名为
{ "name" : "test"}
在 UPDATE
中使用 删除 (-) 和连接 (||) 操作符,例如:
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)
returning *
并非必需品。它只会导致显示所有更新过的行,就像 select
命令一样。 - Manu CJupdate example SET js = JSONB_SET(js::JSONB, '{skill,c++}', js->'skill'->'c', true) where js->'skill' ? 'c';
update example SET js = js#-'{skill, c}' where js->'skill' ? 'c';
- Mahesh我使用以下方法处理嵌套属性,并跳过任何不使用旧名称的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
{path, to, old_name}
的第一个条目上搞砸了,但似乎并没有影响结果,我仍然得到了正确的东西。 - Matheus FelipeCREATE TABLE example(id INT PRIMARY KEY, js JSONB);
INSERT INTO example VALUES
(1, '{"nme": "test"}'),
(2, '{"nme": "second test"}');
UPDATE EXAMPLE
SET js = (REPLACE(js::TEXT, '"nme"', '"name"'))::JSONB
RETURNING *;