重命名Json对象数组中的所有现有属性



我使用Postgres数据库。

例如,有一个表

CREATE TABLE public.json_objects(id serial primary key, objects text);

存储json

数组
INSERT INTO public.json_objects (objects) VALUES ('[{"name":"Ivan"}]'), ('[{"name":"Petr"}, "surname":"Petrov"}]'), ('[{"form":"OOO"}, {"city":"Kizema"}]');

如何替换属性& name"以"名"开头;或";surname"用"第二个名字"。到处都是吗?

我使用update与select -子查询。在这种情况下,将发生替换,但如果json对象中不存在该属性,则它将以空值(这不应该是)添加到json中

WITH updated_table AS (SELECT id, jsonb_agg(new_field_json) as new_fields_json 
FROM (SELECT id, jsonb_array_elements(json_objects.objects::jsonb) - 'name' || jsonb_build_object('first name', jsonb_array_elements(json_objects.objects::jsonb) -> 'name') new_field_json FROM public.json_objects) r group by id) UPDATE public.json_objects SET objects = updated_table.new_fields_json FROM updated_table where json_objects.id = updated_table.id

这似乎是一个单一的操作,所以您可以使用regexp_replace函数来替换键

update table_1 set objects = regexp_replace(objects, '("name"+)', '"first name"');
update table_1 set objects = regexp_replace(objects, '("surname"+)', '"second name"')

dbfiddle

最新更新