如何在javascript / jquery中循环遍历json并正确读取数据

时间:2014-06-06 16:35:46

标签: javascript jquery json

我从serverlet返回了一个json,如下所示:

{
"0": {
    "id": "1252380",
    "text": "This whole #BundyRanch thing stinks to high hell. Can it be a coincidence that Harry Reid n his son have a financial interest in this land?",
    "date": "2014-05-31",
    "name": "Code Green Hackathon",
    "url": "http://pbs.twimg.com/profile_images/424023521040166913/1dAg1g_r_normal.jpeg",
    "username": "t.getScreenName()"
},
"1": {
    "id": "1252378",
    "text": "Harry Reid threatens private property in America http://t.co/uBX7lau0EP via @worldnetdaily",
    "date": "2014-05-31",
    "name": "Murray Leismeister",
    "url": "http://pbs.twimg.com/profile_images/378800000559954056/724415b96df3a22d2a9cc6e2b90052dc_normal.jpeg",
    "username": "t.getScreenName()"
}

}

在javascript中我这样做是为了阅读我的json:

       for(var item in jsresult)
            {
                alert(item);
            }

我希望看到两个警告显示0然后是1但我没有。相反,我得到六个警报分别显示0,1 0,1 0,1,我检查了服务器,我确信唯一的jason返回的是我在上面发布的那个。所以我的javascript代码有问题。任何人都可以帮忙吗?(我很困惑)

更新

这是我的ajax电话

$.get(getServletURLTweet(), {
            timeRange : tRange,
            entities : enIDs,
            topics:tpIDs
        }, function(results) {
            jsresult = jQuery.parseJSON(results);
            for(var item in jsresult)
            {
                alert(item);
            }});

1 个答案:

答案 0 :(得分:1)

你可以试试这个

var data = [ 
 {"Id": 10, "PageName": "home"}, 
 {"Id": 11, "PageName": "about"}, 
 {"Id": 12, "PageName": "more"}
];

$.each(data, function(i, item) {
 alert(data[i].PageName);
});​