1

new to Javascript here.I'm having a little trouble parsing some JSON with JQuery. I believe this is down to the structure of my JSON but as am using these scripts for another service so would like not to have to change there structure.

My JSON is as follows

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

I would ideally like to use customer_name to populate a listview and I would also like to save auto_id somewhere(maybe local storage) so if selected I can present the relevant data.

If anyone could help me structure a loop to parse this JSON I would really appreciate it.

3 Answers 3

3

You can use jQuery to parse it easily.

$.parseJSON(data); 

try this:

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

if you had any problems with it, please let me know

Sign up to request clarification or add additional context in comments.

Comments

1

You can do as follow.

$('#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);
    });
});

You can check out the active working fiddle here. http://jsfiddle.net/amEge/3/

1 Comment

First two answers were great and explain a lot to me which allowed me to access and populate my list but your answer went much further and showed me how to access the id variable on click which is extremely useful, many thanks to everyone.
1

use like this

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

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

working demo : JSON parse with loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.