我有一个带有插入语句的 Postgres 函数,其中一列必须转换为 json 并插入到表中。在这里,我想删除包含 json 对象的双引号。
请帮助说明如何实现它。
replace(json, text, text) doesn't exist
上面的代码出错了 {{1}}。我试图将其转换为文本并删除双引号,但是当我将其转换回 json 时,它再次添加了双引号。
答案 0 :(得分:2)
尝试使用 trim
去除 json 文档周围的双引号:
jsonb_build_array(trim('"' FROM adm_id))
或替换以从每个 json 元素中删除它们:
replace(jsonb_build_array(c)::text,'\"','')
演示:
WITH j (c) AS (
VALUES ('"{id: 1, txt: "foo"}"'),('{id: 2}')
)
SELECT
jsonb_build_array(trim('"' FROM c)),
replace(jsonb_build_array(c)::text,'"','')
FROM j;
jsonb_build_array | replace
---------------------------+-------------------------
["{id: 1, txt: \"foo\"}"] | [\{id: 1, txt: \foo\}\]
["{id: 2}"] | [{id: 2}]
(2 rows)