0

I have converted a csv file to json objects.Now I need to loop through each of the object. But when I try to loop/iterate using for loop it is giving me jsonobject.items is undefined. Could any one suggest a best possible way to iterate through my json?

Below is my code:

function Upload(){

$.ajax({
    url:"Sample.csv" ,
    async: false,
    crossDomain:true,
    success: function (csvd) {
        var wrapper = {};
        var items = $.csv.toObjects(csvd);
        wrapper.items = items;
        alert(wrapper);
        var jsonobject = JSON.stringify(wrapper);
        alert(jsonobject);
        console.log(jsonobject);
        for(k=0;k<jsonobject.items.length;k++){
           }

    },

});
}
Upload()

below is my json

{"items":[{"ID":"1","Name":"John Hammond","Country":"United States"},{"ID":"2","Name":"Mudassar Khan","Country":"India"},{"ID":"3","Name":"Suzanne Mathews","Country":"France"},{"ID":"4","Name":"Robert Schidner","Country":"Russia"}]}
Bruce
  • 565
  • 2
  • 8
  • 23

1 Answers1

1

JSON is a textual notation for data exchange. (More) If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. Loop through items, there's no reason to use JSON.stringify here at all. In fact, there's no need to use JSON here at all.

$.ajax({
  url: "Sample.csv",
  async: false,
  crossDomain: true,
  success: function(csvd) {
    var wrapper = {};
    var items = $.csv.toObjects(csvd);
    wrapper.items = items;
    alert(wrapper);
    // Assuming `wrapper.items` is an array
    wrapper.items.forEach(function(item) {
        // Use `item` here
    });
  }
});

forEach is just one way to loop through an array. This answer goes into detail on the various other ways.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    I think there is no reason to have `wrapper` object either.. __`data exchange`__ seems perfect word to describe `JSON` ;) – Rayon Sep 17 '16 at 08:40