psql insert json with double quotes inside strings
Asked Answered
D

3

11

I'm trying to insert exiftool generated JSON into postgresql via psql which appears valid. It appears somehow that having the escaped single quote and the escaped double quote are not working properly. I can't figure out how to properly escape the json. It appears that psql isn't handling the single quote escape properly as its booting the \" out to the psql instead of the query.

Given this table

create table test (exif jsonb);

These work:

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

But these don't

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.

Any suggestions?

Delacroix answered 28/2, 2016 at 0:22 Comment(0)
M
13

In a database command to escape a single quote you need to double it:

test=> insert into test values ('{"a": 1, "b": "1'' 2\""}');
Matrilateral answered 28/2, 2016 at 0:27 Comment(2)
The double quotes are escaped in the source, and json spec says they should be escaped.Delacroix
Thanks for the follow up @DelacroixMatrilateral
D
3

This is how to do escape the single quote properly:

test=> select '{"a": 1, "b": "1'' 2\""}';
Delacroix answered 28/2, 2016 at 0:27 Comment(0)
O
2

Another option that I found sometimes useful is using $$ as begin and end of string. You still have to escape the double quote in the json.

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

Offal answered 13/6, 2023 at 15:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.