PostgreSQL json 替换 值

临时记录,具体可参考:PostgreSQL小总结

在这里插入图片描述

string 类型

参考自:PostgreSQL 常用函数
在这里插入图片描述

SELECT replace('abcdefabcdef', 'cd', 'XX')
在这里插入图片描述

但是如果类型为 JSON,下面这种执行,就不支持了。

1
2
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
提示:没有函数匹配给定的名称和参数类型。您可能需要添加显式类型强制转换。

UPDATE t_sc_feature_template_rule_copy2 SET rule_json_data=replace(rule_json_data,'store.active=true','store.active=true AND store.if_create_sc=1')
在这里插入图片描述

json 类型

表结构 json 类型

在这里插入图片描述

解释一下这个SQL:

1
2
UPDATE t_sc_feature_template_rule_copy2
SET rule_json_data=replace(rule_json_data::text,'store.active=true','store.active=true AND store.if_create_sc=1')::json

1、::text把字段转为 text 类型,使用 replace 函数进行替换。
2、::json替换完成,因为 replace 函数返回是文本类型,所以要再转为 json

转义符

2021-12-28 16:19:33

1
2
3
4
-- [3] 转义符。在要替换的字符串前面加大写的 E,在内容中'单引号前面加 \ 反斜杠
-- 把 scr.region_type='STORE' 修改为 scr.region_type='BRANCH'
UPDATE t_sc_feature_template_rule
SET rule_json_data=replace(rule_json_data::text,E'scr.region_type=\'STORE\'',E'scr.region_type=\'BRANCH\'')::json;