在Postgres JSONB字段中全局替换

问题描述 投票:2回答:1

我需要全局替换嵌套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,三重转义引号。

任何想法如何做到这一点?

json postgresql postgresql-9.6
1个回答
4
投票

使用简单的强制转换为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)
© www.soinside.com 2019 - 2024. All rights reserved.