如何在循环中解析JSON

时间:2013-02-28 11:48:31

标签: jquery json jquery-mobile

这里是Javascript的新手。我在使用JQuery解析一些JSON时遇到了一些麻烦。我相信这取决于我的JSON结构,但是我将这些脚本用于其他服务,所以不希望改变那里的结构。

我的JSON如下

{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack   Black","auto_id":"22"}]}

我最好使用customer_name来填充listview,我还想在某处保存auto_id(可能是本地存储),所以如果选中,我可以提供相关数据。

如果有人可以帮我构建一个解析这个JSON的循环,我真的很感激。

3 个答案:

答案 0 :(得分:3)

您可以使用jQuery轻松解析它。

$.parseJSON(data); 

试试这个:

var json = $.parseJSON(data);
for(var i=0; i<json.customerInAccount.length; i++){
     // do your stuff here..
}

如果您有任何问题,请告诉我

答案 1 :(得分:1)

像这样使用

var value=yourJsonString
var results=JSON.parse(value); 

$.each(results.customerInAccount,function(i,item){
 // do with item 
alert(  item.customer_name);
});

工作演示:JSON parse with loop

答案 2 :(得分:1)

你可以这样做。

$('#home').live('pageshow', function(){
    // creating object 
    var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack   Black","auto_id":"22"}]}');

    // creating html string
    var listString = '<ul data-role="listview" id="customerList">';

    // running a loop
    $.each(customerList.customerInAccount, function(index,value){
     listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
    });
    listString +='</ul>';

    console.log(customerList);

    //appending to the div
    $('#CustomerListDiv').html(listString);

    // refreshing the list to apply styles
    $('#CustomerListDiv ul').listview();

    // getting the customer id on the click
    $('#customerList a').bind('click',function(){
     var customerID = $(this).data('cusid');  
     alert(customerID);
    });
});

你可以在这里看看活跃的工作小提琴。 http://jsfiddle.net/amEge/3/