Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Escape double quotes in query result

I have a CONCATENATION problem regarding quotes. In my database I have single and double quoted text and then I buld a JSON string with CONCAT,

CONCAT('{"',a,'":"',b,'"}')

Lets say we have the following data:

a           b
Phrase      Monica's mirror
Phrase      Joe "Hammer" Smith
Phrase      Oo-la-laaa

The concatenation will be

{"Phrase":"Monica's mirror"}
{"Phrase":"Joe "Hammer" Smith"}
{"Phrase":"Oo-la-laaa"}

As you can see 'Joes "Hammer" Smith' will create an invalid json string.

QUESTION

Is there a way in SQL to escape quotes (in the CONCAT)? so I get this result:

{"Phrase":"Monica's mirror"}
{"Phrase":"Joe \"Hammer\" Smith"}
{"Phrase":"Oo-la-laaa"}

Remember, this is not on the PHP side, it needs to be done in the SQL query,
Thank you...

like image 876
Max Kielland Avatar asked Feb 20 '11 22:02

Max Kielland


People also ask

Do you have to escape double quotes in SQL?

Use two single quotes to escape them in the sql statement. The double quotes should not be a problem: SELECT 'How is my son''s school helping him learn? "Not as good as Stack Overflow would!"'

How do I escape a character in MySQL?

MySQL recognizes the following escape sequences. \0 An ASCII NUL (0x00) character. \' A single quote (“'”) character. \" A double quote (“"”) character.

How do you escape a string in a query?

Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.


1 Answers

Have you tried something like this?

CONCAT('{"',REPLACE(a,'"','\\"'),'":"',REPLACE(b,'"','\\"'),'"}')
like image 113
Mārtiņš Briedis Avatar answered Sep 26 '22 14:09

Mārtiņš Briedis