在 Postgres JSONB 字段中全局替换
Globally replace in Postgres JSONB field
我需要全局替换嵌套 JSON 结构中多个位置出现的特定字符串,该字符串在 postgres table 中存储为 jsonb。例如:
{
"location": "tmp/config",
"alternate_location": {
"name": "config",
"location": "tmp/config"
}
}
...应该变成:
{
"location": "tmp/new_config",
"alternate_location": {
"name": "config",
"location": "tmp/new_config"
}
}
我试过:
UPDATE files SET meta_data = to_json(replace(data::TEXT, 'tmp/config', 'tmp/new_config'));
不幸的是,这会导致格式错误 JSON,带有三重转义引号。
知道怎么做吗?
使用简单的转换为 jsonb
而不是 to_json()
,例如:
with files(meta_data) as (
values(
'{
"location": "tmp/config",
"alternate_location": {
"name": "config",
"location": "tmp/config"
}
}'::jsonb)
)
select replace(meta_data::text, 'tmp/config', 'tmp/new_config')::jsonb
from files;
replace
--------------------------------------------------------------------------------------------------------
{"location": "tmp/new_config", "alternate_location": {"name": "config", "location": "tmp/new_config"}}
(1 row)
使用更新:
UPDATE files SET meta_data = replace(data::TEXT, 'tmp/config', 'tmp/new_config')::jsonb;
我需要全局替换嵌套 JSON 结构中多个位置出现的特定字符串,该字符串在 postgres table 中存储为 jsonb。例如:
{
"location": "tmp/config",
"alternate_location": {
"name": "config",
"location": "tmp/config"
}
}
...应该变成:
{
"location": "tmp/new_config",
"alternate_location": {
"name": "config",
"location": "tmp/new_config"
}
}
我试过:
UPDATE files SET meta_data = to_json(replace(data::TEXT, 'tmp/config', 'tmp/new_config'));
不幸的是,这会导致格式错误 JSON,带有三重转义引号。
知道怎么做吗?
使用简单的转换为 jsonb
而不是 to_json()
,例如:
with files(meta_data) as (
values(
'{
"location": "tmp/config",
"alternate_location": {
"name": "config",
"location": "tmp/config"
}
}'::jsonb)
)
select replace(meta_data::text, 'tmp/config', 'tmp/new_config')::jsonb
from files;
replace
--------------------------------------------------------------------------------------------------------
{"location": "tmp/new_config", "alternate_location": {"name": "config", "location": "tmp/new_config"}}
(1 row)
使用更新:
UPDATE files SET meta_data = replace(data::TEXT, 'tmp/config', 'tmp/new_config')::jsonb;