I have json encoded data that can have the following format: {"forumla": "callTo(\"par1\", \"par2\")"} When I try to insert it into a postgresql table with a jsonb column, I get the following Error:
SQL error QSqlError(-1, "QPSQL: Unable to create query", "ERROR: invalid input syntax for type json
LINE 1: ...15-12-11 15:20:17.350', 21590, '{ "forumla...
^
DETAIL: Token "par1" is invalid.
CONTEXT: JSON data, line 1: ..." : "callTo(\\"par1...
")
It seems like Qt somehow replaced the escaped quotes (\") with an escaped backslash and a quote. Inserting the string via the psql cli works. Can someone help me with this?
Thanks in advance.
Update:
I removed the binding and replace the double backslash with a single one.
Now I could insert the value successfully.
QSqlField f(name, QVariant::String);
f.setValue(fields.value(name));
const QString value = db.driver()->formatValue(f).replace("\\\\", "\\");
The problem stems probably from Qt (at least pre 5.x) not knowing about json in databases. So it can only treat it as a string and sees the need to escape backslashes.
This is obviously not an ideal solution.
Update 2:
I found an acceptable solution. Qt (at least 4.7) assumes a backslash to be a special character in a string value. This is no longer the case (by default) since 9.1. See http://www.postgresql.org/docs/9.4/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-ESCAPE
So I had to set the following so Postgresql again assumes \ to be an escaped backslash:
QSqlQuery query(db);
query.exec("SET standard_conforming_strings TO false");