Reputation: 4522
After reading a number of questions on parsing an object in javascript I'm still having issues with parsing the following query response:
{"messagesProfile": "[{\"message\": \"This is a test message\", \"sender\": \"[email protected]\", \"receiver
\": \"[email protected]\"}, {\"message\": \"This is a second test message\", \"sender\": \"[email protected]
\", \"receiver\": \"[email protected]\"}, {\"message\": \"This is a third test message\", \"sender\": \"test
@test.com\", \"receiver\": \"[email protected]\"}]", "successProfileMessages": true}
The code that parses the above response is:
if(data.successProfileMessages === false) {
alert("Failed to retrieve messages");
} else {
if(typeof data.messagesProfile != "undefined" && data.messagesProfile != null && data.messagesProfile.length > 0) {
messages = messages + "<tr>";
messages = messages + "<td>";
messages = messages + "There are no messages yet!";
messages = messages + "</td>";
messages = messages + "<td>";
} else {
// Successfully retrieved messages
for(var i in data) {
messages = messages + "<tr>";
messages = messages + "<td>";
messages = messages + data.messagesProfile.sender[i];
messages = messages + "</td>";
messages = messages + "<td>";
messages = messages + data.messagesProfile.message[i];
messages = messages + "</td>";
messages = messages + "</tr>";
}
}
}
How is it possible to unescape the escaped double quotes and iterate through the JSON object's array fields?
"[{\"message\": \"This is a test message\", \"sender\": \"[email protected]\", \"receiver
\": \"[email protected]\"}, {\"message\": \"This is a second test message\", \"sender\": \"[email protected]
\", \"receiver\": \"[email protected]\"}, {\"message\": \"This is a third test message\", \"sender\": \"test
@test.com\", \"receiver\": \"[email protected]\"}]"
Upvotes: 0
Views: 1155
Reputation:
the messageProfile property of data
is a string so you need to parse it
you can do this in the else
clause
var arrayResult = JSON.parse(data.messagesProfile);
for (var i = 0, len = arrayResult.length; i < len; i++) {
var item = arrayResult[i];
// do your stuff
}
For iterating over an array i discourage the use of for (var i in arrayResult)
cause it will not give you the desired result. It will iterate through all the properties of the object (including the length property!!!!!)
Upvotes: 2