我需要全局替换嵌套 JSON 结构中多个位置出现的特定字符串,该字符串作为 jsonb 存储在 postgres 表中。例如:
{
"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()
, e.g.:
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)