Wednesday, 14 March 2012

JSON and SQL

I have a project where, for auditing purposes, I serialise a JavaScript object to JSON and then store the resulting string in a MySQL database table.

Recently I encountered a problem with de-serialising some of these strings back to objects. The problem was that a string field in one of the instances contained embedded quotes and these were not escaped in the SQL table. After a little while spent digging about I realised what the problem was.

When JSON.stringify is called on a string, any embedded double-quote characters are escaped, so the string 'This contains "double quoted" text' becomes 'This contains \"double quoted\" text'. This is all fine, but when you add a string to the database the escape character is treated as an escape and is removed from the resulting string. If you then read the string back out and try to JSON.parse it the un-escaped double-quotes cause it to fail. To keep the escape character you need to escape the escapes before adding to the database.

You also need to escape any single quote characters before adding to a database table.

Try:
 JSON.stringify(obj).replace(/'/g, "\'").replace(/\\/g, "\\\\");