1

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

The backslashes are getting lost during the retrieval, I have solved the issue with a REPLACE on the SELECT on MySQL but this kind of code looks dumb: REPLACE(field, "\\\\", "\\\\\\\\")
They shouldn't be getting lost there... I'm not entirely sure what to suggest without seeing the full query code.
Damn... the issue was with this function: stackoverflow.com/questions/7744912/… - I was doing a full "back to basics" test when I found that some "%" get escaped when it doesn't need to be scaped ¬¬ the query works great without the replace using this lib: github.com/felixge/node-mysql
stackoverflow etiquette requires that you accept this answer, since it led to you solving your problem.
1

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!

Comments

0

Use encodeURI() and decodeURI() to save nested JSON in SQL database. This will escape everything for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.