My goal is simply to convert a JavaScript object to JSON and insert it into a MySQL row that stores the MySQL JSON data type. This process must happen as part of a large batch insert, so I cannot edit the data manually. When call JSON.stringify on the object, I get valid JSON, but, because the object contains song lyrics that often contain single quotes, when I try to run the SQL query, MySQL throws a parse error.
This works fine
const validJson = '{"foo": "bar", "buzz": 1}';
INSERT INTO table_name ( songid, json )
VALUES ( ${song.songid}, ${validJson} );
But, this doesn’t
const validJsonWithASingleQuote = {"foo's": "bar", "buzz": 1}';
INSERT INTO table_name ( songid, json )
VALUES ( ${song.songid}, ${validJsonWithASingleQuote} );
I also tried using a prepared statement with no luck
PREPARE myInsert FROM 'INSERT INTO table_name ( songid, json ) VALUES ( ?, ? )';
SET @a = ${song.songid};
SET @b = ${JSON.stringify(r)};
EXECUTE myInsert USING @a, @b;
I should also mention, that the original JavaScript objects contain strings that have single quotes escaped with "\". The JSON.stringify method, decodes those backslashes.
Unfortunately, all of the SO questions I have found on this topic either recommend escaping single quotes with "\" manually or they have gone unresolved. Is there a programatic way to accomplish this? Perhaps a JavaScript or MySQL method that would generate valid JSON and leave the "\'" sequences in?