更新 postgres 数组中的每个值 json
Update every value in an array in postgres json
在我的 postgres 数据库中,我有 json 看起来类似于:
{
"myArray": [
{
"myValue": 1
},
{
"myValue": 2
},
{
"myValue": 3
}
]
}
现在我想将 myValue
重命名为 otherValue
。我不能确定数组的长度!最好我想使用 set_jsonb
之类的东西和通配符作为数组索引,但这似乎不受支持。那么最好的解决方案是什么?
您必须分解整个 jsonb 对象,修改单个元素并重新构建对象。
自定义函数会有帮助:
create or replace function jsonb_change_keys_in_array(arr jsonb, old_key text, new_key text)
returns jsonb language sql as $$
select jsonb_agg(case
when value->old_key is null then value
else value- old_key || jsonb_build_object(new_key, value->old_key)
end)
from jsonb_array_elements(arr)
$$;
使用:
with my_table (id, data) as (
values(1,
'{
"myArray": [
{
"myValue": 1
},
{
"myValue": 2
},
{
"myValue": 3
}
]
}'::jsonb)
)
select
id,
jsonb_build_object(
'myArray',
jsonb_change_keys_in_array(data->'myArray', 'myValue', 'otherValue')
)
from my_table;
id | jsonb_build_object
----+------------------------------------------------------------------------
1 | {"myArray": [{"otherValue": 1}, {"otherValue": 2}, {"otherValue": 3}]}
(1 row)
使用json函数绝对是最优雅的,但是你可以通过使用字符替换来解决。将 json(b) 转换为文本,执行替换,然后将其改回 json(b)。在此示例中,我包含引号和冒号以帮助文本替换目标 json 键而不与值冲突。
CREATE TABLE mytable ( id INT, data JSONB );
INSERT INTO mytable VALUES (1, '{"myArray": [{"myValue": 1},{"myValue": 2},{"myValue": 3}]}');
INSERT INTO mytable VALUES (2, '{"myArray": [{"myValue": 4},{"myValue": 5},{"myValue": 6}]}');
SELECT * FROM mytable;
UPDATE mytable
SET data = REPLACE(data :: TEXT, '"myValue":', '"otherValue":') :: JSONB;
SELECT * FROM mytable;
在我的 postgres 数据库中,我有 json 看起来类似于:
{
"myArray": [
{
"myValue": 1
},
{
"myValue": 2
},
{
"myValue": 3
}
]
}
现在我想将 myValue
重命名为 otherValue
。我不能确定数组的长度!最好我想使用 set_jsonb
之类的东西和通配符作为数组索引,但这似乎不受支持。那么最好的解决方案是什么?
您必须分解整个 jsonb 对象,修改单个元素并重新构建对象。
自定义函数会有帮助:
create or replace function jsonb_change_keys_in_array(arr jsonb, old_key text, new_key text)
returns jsonb language sql as $$
select jsonb_agg(case
when value->old_key is null then value
else value- old_key || jsonb_build_object(new_key, value->old_key)
end)
from jsonb_array_elements(arr)
$$;
使用:
with my_table (id, data) as (
values(1,
'{
"myArray": [
{
"myValue": 1
},
{
"myValue": 2
},
{
"myValue": 3
}
]
}'::jsonb)
)
select
id,
jsonb_build_object(
'myArray',
jsonb_change_keys_in_array(data->'myArray', 'myValue', 'otherValue')
)
from my_table;
id | jsonb_build_object
----+------------------------------------------------------------------------
1 | {"myArray": [{"otherValue": 1}, {"otherValue": 2}, {"otherValue": 3}]}
(1 row)
使用json函数绝对是最优雅的,但是你可以通过使用字符替换来解决。将 json(b) 转换为文本,执行替换,然后将其改回 json(b)。在此示例中,我包含引号和冒号以帮助文本替换目标 json 键而不与值冲突。
CREATE TABLE mytable ( id INT, data JSONB );
INSERT INTO mytable VALUES (1, '{"myArray": [{"myValue": 1},{"myValue": 2},{"myValue": 3}]}');
INSERT INTO mytable VALUES (2, '{"myArray": [{"myValue": 4},{"myValue": 5},{"myValue": 6}]}');
SELECT * FROM mytable;
UPDATE mytable
SET data = REPLACE(data :: TEXT, '"myValue":', '"otherValue":') :: JSONB;
SELECT * FROM mytable;