我需要全局替换在嵌套JSON结构中出现多个位置的特定字符串,这些字符串存储为postgres表中的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,三重转义报价。
任何想法如何做到这一点?
答案 0 :(得分:3)
使用简单的强制转换为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)