Gunesh.John
Gunesh.John

Reputation: 95

Pass a json list to array in javascript error

I am trying to pass a list in from json to a javascript. I get this error:

04-03 08:35:49.867: E/NONE(2861): exception. TypeError: Cannot read property 'files' of undefined

The list is as follows:

{"data":"{\"files\":[{\"name\":\"doc1.pdf\",\"title\":\"networking\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc1.pdf\"},{\"name\":\"doc2.pdf\",\"title\":\"Armoogum\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc2.pdf\"}]}","isSuccessful":true}

The code is here:

var arrayResults = res.responseJSON.data;
alert(arrayResults.length);
var full_list="";
for(var i=0;i<arrayResults.length;i++){ 
  full_list =  full_list + arrayResults[i].data.files.name + "<br />" +  arrayResults[i].data.files.title + '<br />' +  arrayResults[i].data.files.path + '<br />';
  $("#viewlist").html(full_list);  
}

Upvotes: 0

Views: 50

Answers (1)

Hitmands
Hitmands

Reputation: 14179

this should work:

var result = {"data":"{\"files\":[{\"name\":\"doc1.pdf\",\"title\":\"networking\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc1.pdf\"},{\"name\":\"doc2.pdf\",\"title\":\"Armoogum\",\"path\":\"mfpreader.comze.com\\\/files\\\/doc2.pdf\"}]}","isSuccessful":true};

var files = JSON.parse(result.data).files;
var str = '';

for(var file, i = 0; i < files.length; i++) {
  file = files[i];
  
  str += file.name + '<br>';
}

document.write(str);

Upvotes: 2

Related Questions