2013-02-28 76 views
1

Javascript to this here。我在使用JQuery解析某些JSON時遇到了一些麻煩。我相信這是由我的JSON結構決定的,但是我正在使用這些腳本來處理其他服務,所以我們不需要改變那裏的結構。如何在循環中解析JSON

我的JSON是如下

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

我會非常喜歡用CUSTOMER_NAME來填充ListView和我也想保存auto_id地方(也許本地存儲),所以如果選擇我可以提出相關數據。

如果有人可以幫我構建一個循環來解析這個JSON,我會非常感激。

回答

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/

+0

前兩個答案很好,向我解釋很多,這讓我能夠訪問和填充我的列表,但您的答案更進一步,並告訴我如何訪問id變量,這是非常有用的,非常感謝大家。 – user1668630 2013-02-28 14:39:47

+0

很高興幫助你:) – 2013-03-01 05:41:36

3

您可以使用jQuery輕鬆解析它。

$.parseJSON(data); 

試試這個:

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

如果您有任何問題,請讓我知道

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