Search code examples
javascriptjqueryreplaceall

Replace \" with " in Javascript


I have a JSON from my web server that I obtain from a XMLHttpRequest. The data has the following form when I print it out using

var data = this.responseText;
console.log("data=" + JSON.stringify(data));

data=[{\"day\":0,\"periods\":[\"0xffffffffffff\"]}]

I process the JSON using jquery but I'm getting an error: Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"day":0,"periods":["0xffffffffffff"]}]

I'm assuming the problem is due to the escaping of the quotes as if I hard code data to [{"day":0,"periods":["0xffffffffffff"]}] I don't get the error.

I've tried various ways of getting rid of the escape but without success:

data = data.replace(/\\/g, ""); 

Does not modify the string at all; I found a function from another thread, replaceAll, but this:

var newData = data.replaceAll("\\","");

..made no difference either.

Trying to replace \" with ' then replacing the ' with " just returns me to \"

var newData = data.replaceAll("\"","'");

now newData = [{'day':0,'periods':['0xffffffffffff']}]

newData = newData.replaceAll("'","\"");

and it's back to [{\"day\":0,\"periods\":[\"0xffffffffffff\"]}]

Trying to process with single quote, i.e. [{'day':0,'periods':['0xffffffffffff']}] gives me the same Uncaught TypeError message.

Any ideas how I can solve this?

Thanks.


Solution

  • The error is that you are using JSON.stringify on a string. Have an exact look on this.responseText - responseText - that you are using as property. Just change it to

    var data = JSON.parse(this.responseText); 
    console.log("data=" + data);