0

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.

1
  • /\/ would be the same as // since \ is an escape. Try /\\/. But best thing would be to fix the server giving invalid JSON out. Or is the problem that you’re trying to stringify the data when you should be parsing it? Commented Feb 18, 2018 at 12:00

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this was the solution. The JSON now gets correctly processed.

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.