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

前端之家收集整理的这篇文章主要介绍了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\""} |

猜你在找的JavaScript相关文章