kageoni
kageoni

Reputation: 45

JSON Escaping double quotes not working

I'm getting errors on a screen when it's trying to eval some json, it's giving me the error unexpected identifier..

The data causing the issue and how it's coming back when I check the Json response is:

"itemDescription":"STANDARD \"B\" RED BOX",

I'm using the below code in the java to handle the double quotes:

itemDescription = itemDescription.replaceAll("\\r|\\n", "");
itemDescription = itemDescription.replaceAll("\"", "\\\\\"");
itemDescription = itemDescription.replaceAll("'", "'");

Any idea why this wouldn't be working? If I remove the double quotes, I no longer get any errors.

Item descriptions such as "itemDescription":"STANDARD 16\" RED BOX" go through fine..

Thanks!

Upvotes: 2

Views: 608

Answers (2)

Mouad EL Fakir
Mouad EL Fakir

Reputation: 3749

Try to use StringEscapeUtils :

itemDescription  = StringEscapeUtils.escapeJson(itemDescription);

Upvotes: 0

Sylvain
Sylvain

Reputation: 417

You need two more backslashes at line 2:

itemDescription = itemDescription.replaceAll("\"", "\\\\\\\"").

So that " is replaced by \\\" and not \\".

Upvotes: 2

Related Questions