1
var str = '{"Language":"en","Type":"General","Text":""Mela" means "apple" in Italian"}';

Now JSON.parse(str) throws this error

Uncaught SyntaxError: Unexpected token M in JSON at position 43

Now replacing quotes escapes whole string and parsed JSON is not usable anymore

str = str.replace(/\\([\s\S])|(")/g,"\\$1$2");

"{\"Language\":\"en\",\"Type\":\"General\",\"Text\":\"\"Mela\" means \"apple\" in Italian\"}"

Other solutions like below do not seem to be working in this scenario

How to escape a JSON string containing newline characters using JavaScript?

Vishvendra Singh
  • 484
  • 5
  • 19

3 Answers3

0

You need to add a backslash before each double quote within your string as:

const str = '{"Language":"en","Type":"General","Text": "\\"Mela\\" means \\"apple\\" in Italian"}';

const obj = JSON.parse(str)
console.log(obj.Text)
Hemerson Carlin
  • 7,354
  • 1
  • 27
  • 38
0

In JSON you don't escape double quotes of the property name or the begging of the property value, just escape what's inside property value:

{\"Text\":\"\"Mela\" means ....

It should be like this:

{"Text":"\"Mela\" means ....
Dabbas
  • 3,112
  • 7
  • 42
  • 75
0

This can be done with multiple replacements:

var str = '{"Language":"en","Type":"General","Text":""Mela" means "apple" in Italian"}';
str = str.replace(/"/,"'"); //Replace all " with '

str = str.replace(/{'/,'{"') //Restore " to start of JSON
str = str.replace(/','/,'","'); //Restore " around JSON , separators
str = str.replace(/':'/,'":"'); //Restore " around JSON : separators
str = str.replace(/'}/,'"}'); //Restore " to end of JSON
str = str.replace(/'/,'\"'); //All remaining ' must be inside of data, so replace with properly escaped \"

console.log(str);

EDIT: A problem with this solution is that is will also replace original ' characters with " inside the text.