在psql中插入带有双引号的字符串的json

10
我正在尝试通过psql将由exiftool生成的JSON插入到PostgreSQL中,该JSON似乎是有效的。 但是,转义的单引号和双引号似乎无法正常工作。我无法弄清楚如何正确转义json。出现问题的地方在于,psql不能正确处理单引号的转义,因为它会将\"发送到psql而不是查询中。
给定这个表:
create table test (exif jsonb);

这些功能有效:

test=> insert into test values ('{"a": 1, "b": "2"}');
INSERT 0 1
test=> insert into test values ('{"a": 1, "b": "2\""}');
INSERT 0 1
test=> select * from test;
     exif
----------------------
{"a": 1, "b": "2"}
{"a": 1, "b": "2\""}

但是这些并不

test=> insert into test values ('{"a": 1, "b": "1\' 2\""}');
Invalid command \""}');. Try \? for help.

test=> select '{"a": 1, "b": "1' 2\""}';
Invalid command \""}';. Try \? for help.

test=> select E'{"a": 1, "b": "1' 2\""}';
Invalid command \""}';. Try \? for help.

test=> select '{"a": 1, "b": "1\' 2\""}';
Invalid command \""}';. Try \? for help.

有什么建议吗?
3个回答

12

在数据库命令中,为了转义单引号,您需要将其加倍:

test=> insert into test values ('{"a": 1, "b": "1'' 2\""}');

双引号在源代码中已经被转义,而 JSON 规范要求它们必须被转义。 - ruckc
感谢@ruckc的跟进。 - Jorge Campos

3

以下是正确转义单引号的方法:

test=> select '{"a": 1, "b": "1'' 2\""}';

1
另一个我发现有时候很有用的选项是使用$$作为字符串的起始和结束符号。在json中,你仍然需要转义双引号。

insert into test values ($${"a": 1, "b": "1' 2""}$$);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接