MySQL Escape double quotes as a result of a query

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

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

Suppose we have the following data:

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

Concatenation will be

{"Phrase":"Monica 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 CONCAT)? so I get this result:

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

Remember that this is not on the side of PHP, it needs to be done in the SQL query,
Thanks ...

+3
source share
1 answer

Have you tried something like this?

CONCAT('{"',REPLACE(a,'"','\\"'),'":"',REPLACE(b,'"','\\"'),'"}')
+7
source

Source: https://habr.com/ru/post/1793465/


All Articles