【问题标题】:Globally replace in Postgres JSONB field在 Postgres JSONB 字段中全局替换
【发布时间】:2018-05-23 01:52:00
【问题描述】:

我需要全局替换出现在嵌套 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 格式错误,带有三重转义引号。

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

【问题讨论】:

  • 这不是一个有效的 JSON。
  • @klin,哎呀,我让示例 json 有效。

标签: json postgresql jsonb postgresql-9.6


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 2023-01-29
    • 2017-03-14
    相关资源
    最近更新 更多