Aparna Aparna - 2 months ago 4
JSON Question

convert csv to json objects and loop through each of the objects not working

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"}]}

Answer

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.

Comments