Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psql insert json with double quotes inside strings

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?

like image 676
ruckc Avatar asked Feb 28 '16 00:02

ruckc


People also ask

How do I allow double quotes in JSON?

if you want to escape double quote in JSON use \\ to escape it.

Can you use double quotes in PostgreSQL?

In PostgreSQL, double quotes (like "a red dog") are always used to denote delimited identifiers. In this context, an identifier is the name of an object within PostgreSQL, such as a table name or a column name. Delimited identifiers are identifiers that have a specifically marked beginning and end.

How do you escape double quotes in Postgres?

Quotes and double quotes should be escaped using \.

How do I insert a quote in PostgreSQL?

In Postgresql, we can insert a single quote using the double single quote (”) or (E'\') to declare Posix escape string syntax.


1 Answers

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

test=> insert into test values ('{"a": 1, "b": "1'' 2\""}');
like image 176
Jorge Campos Avatar answered Nov 02 '22 21:11

Jorge Campos