Mingle Li
Mingle Li

Reputation: 1380

Accessing a value in nested JSON objects and arrays

I'm using Blueimp's JQuery File Upload plugin, and so upon successful upload the callback function is:

$('#fileupload').fileupload('send', {files: filesList})
    .success(function (result, textStatus, jqXHR) { console.log('success'); })
    .error(function (jqXHR, textStatus, errorThrown) { console.log('error'); })
    .complete(function (result, textStatus, jqXHR) { 
        console.log('complete: ' + JSON.stringify(result));
        console.log(result.responseText.files[0].name);
});

So all I'm looking at is the .complete function. The first console.log returns:

complete: {"readyState":4,"responseText":"{"files":[{"name":"video.mp4","type":"video/mp4","size":2348842}]}","responseJSON":{"files":[{"name":"video.mp4","type":"video/mp4","size":2348842}]},"status":201,"statusText":"Created"}

complete is technically result, and under that is responseText and under that is files, which is an array, and name is a key/property in that array.

So when I try to console.log result.responseText.files[0].name, it says Uncaught TypeError: Cannot read property '0' of undefined.

Could someone please find what's wrong? Thanks!

Upvotes: 0

Views: 43

Answers (1)

tato
tato

Reputation: 5559

result.responseText is a string

you need to convert to an object: JSON.parse(result.responseText)

response = JSON.parse(result.responseText);
console.log(response.files[0].name);

will work

Upvotes: 3

Related Questions