微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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\""} |

原文地址:https://www.jb51.cc/js/150172.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐