Ad

Accessing A Value In Nested JSON Objects And Arrays

- 1 answer

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.logresult.responseText.files[0].name, it says Uncaught TypeError: Cannot read property '0' of undefined.

Could someone please find what's wrong? Thanks!

Ad

Answer

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

Ad
source: stackoverflow.com
Ad