Reputation: 4784
Let's say I have an object:
person={'name':'john "Garfield"'};
And I convert it to a string:
JSON.stringify(person);
// RESULT: {"name":"john \"Garfield\""}
And then I store that string on MySQL or anything else and later I get that string on node.js (using interactive console):
string = '{"name":"john \"Garfield\""}';
// RESULT: {"name":"john "Garfield""}
Then I parse the object:
JSON.parse(string);
RESULT: SyntaxError: Unexpected token G
How can I parse stored json stringified string? I have them on MySQL and they loose their scaping slashes when requested by the MySQL library.
Upvotes: 1
Views: 2757
Reputation: 11
Use encodeURI()
and decodeURI()
to save nested JSON in SQL database. This will escape everything for you.
Upvotes: 0
Reputation: 4784
I have solved this issue with a REPLACE on MySQL, I don't understand why this have to be done this way, well, I understand but I don't like this solution, using node.js, and a MySQL library and calling MySQL from node here is the statement I did:
REPLACE(`field`, "\\\\", "\\\\\\\\") as field2
This looks dumb, but when you declare a string on node it is automatically unescaped, then this:
string = 'REPLACE(`field`, "\\\\", "\\\\\\\\") as field2';
becomes this:
REPLACE(`field`, "\\", "\\\\") as field2
And when is received by MySQL it becomes:
REPLACE(`field`, "\", "\\") as field2
I feel that it has to be another way!
Upvotes: 1
Reputation: 324840
You (should) notice that the backslashes have "gone missing" when you have the string. If it's stored in the database and retrieved from the database then the code should be working just fine. However, if you manually input that string to parse it out, then you need to escape the backslashes.
string = '{"name":"John \\"Garfield\\""}';
If the backslashes are getting lost during the MySQL insert, then try escaping them before inserting them.
Upvotes: 3