Postgres row_to_json生成带有双重转义引号的无效JSON

创建 JSON导出时,Postgres会错误地引用引号.请注意以下更新中的双引号…
UPDATE models SET column='"hello"' WHERE id=1;

copY (SELECT row_to_json(models)
    FROM (SELECT column FROM shaders WHERE id=1) shaders)
    TO '/output.json';

output.json的内容

{"column":"\\"hello\\""}

您可以看到引号被不正确地转义,并且它会创建无效的JSON.
它应该是:

{"column":"\"hello\""}

我该如何解决这个Postgres错误解决它?

解决方法

这与JSON无关.它是关于copY命令中文本格式(认)处理反斜杠的方式.从 the PostgreSQL documentation – COPY开始:

Backslash characters (\) can be used in the copY data to quote data characters that might otherwise be taken as row or column delimiters. In particular,the following characters must be preceded by a backslash if they appear as part of a column value: backslash itself,newline,carriage return,and the current delimiter character.

(强调我的.)
您可以使用CSV格式并将引号字符从doublequote更改为其他内容解决此问题.

展示:

SELECT row_to_json(row('"hello"'))
 | "{"f1":"\"hello\""}" |
copY (SELECT row_to_json(row('"hello"'))) TO '/output.json';
 | {"f1":"\\"hello\\""} |
copY (SELECT row_to_json(row('"hello"'))) TO '/output.json' CSV QUOTE '$';
 | {"f1":"\"hello\""} |

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...