简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM