json - 在 Postgres JSONB 字段中全局替换

标签 json postgresql jsonb postgresql-9.6

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

有什么办法吗?

最佳答案

使用简单的转换为 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)

关于json - 在 Postgres JSONB 字段中全局替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47720767/

相关文章:

mysql - 我应该在大型 EAV 表中使用时间戳还是单独的时间列?

postgresql - PostgreSQL 上的 CTE 和临时索引

postgresql - postgres jsonb 列中的模糊字符串匹配

javascript - JSON.stringify() 和 JSON2.stringify() 的区别?

python - 将弹出窗口添加到 folium 中的 geojson 层

string - 奇怪的修剪功能行为

postgresql - 为什么设计注册#create,:trackable doing an INSERT instead of UPDATE?

postgresql - 如何使用 PostgreSQL 将变量放入 JSONB?

Python请求Json数据,想将其从excel复制回csv文件

java - JSONObject 类出现问题,未给出错误