在javascript中解析带有转义双引号属性的JSON对象

时间:2015-10-15 16:04:49

标签: javascript jquery parsing

reading number questions URL Rewrite module解析javascript中的对象后,我仍然遇到解析以下查询响应的问题:

{"messagesProfile": "[{\"message\": \"This is a test message\", \"sender\": \"test@test.com\", \"receiver
\": \"test@test.com\"}, {\"message\": \"This is a second test message\", \"sender\": \"test@test.com
\", \"receiver\": \"test@test.com\"}, {\"message\": \"This is a third test message\", \"sender\": \"test
@test.com\", \"receiver\": \"test@test.com\"}]", "successProfileMessages": true}

解析上述响应的代码是:

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>";
                }
            }
        }

如何绕过转义的双引号并遍历JSON对象的数组字段?

"[{\"message\": \"This is a test message\", \"sender\": \"test@test.com\", \"receiver
\": \"test@test.com\"}, {\"message\": \"This is a second test message\", \"sender\": \"test@test.com
\", \"receiver\": \"test@test.com\"}, {\"message\": \"This is a third test message\", \"sender\": \"test
@test.com\", \"receiver\": \"test@test.com\"}]"

1 个答案:

答案 0 :(得分:2)

data的messageProfile属性是一个字符串,因此您需要解析它

您可以在else子句

中执行此操作
var arrayResult = JSON.parse(data.messagesProfile);
for (var i = 0, len = arrayResult.length; i < len; i++) {
  var item = arrayResult[i];
  // do your stuff
}

对于迭代数组,我不鼓励使用for (var i in arrayResult),因为它不会给你想要的结果。它将遍历对象的所有属性(包括length属性!!!!!)