I have been working on a script to fetch the duration of a YouTube video using its id
.
Here is the code snippet I've written:
var vidID = "";
var vidData;
var vidDuration;
function getResponse() {
$.getJSON( "https://www.googleapis.com/youtube/v3/videos?id=unSlPx7Zu-w&part=contentDetails&key=AIzaSyCSMBWe5CbW122szJGvGjQ6UrktPL4Z0Mw", function( data ) {
var items = [];
vidDuration = data;
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$('body').append (JSON.stringify(data));
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
getResponse();
console.log(vidDuration.items[0][contentDetails][duration]);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js"></script>
</body>
</html>
Console Results:
"error"
"TypeError: Cannot read property 'items' of undefined
at felepivuni.js:28:50
at https://static.jsbin.com/js/prod/runner-4.1.4.min.js:1:13924
at https://static.jsbin.com/js/prod/runner-4.1.4.min.js:1:10866"
The script seems to be functioning correctly as it provides the expected output of stringified JSON and two main JSON objects.
However, there are issues with displaying '[Object object]' twice in the result.
This is the structure of the response packet we receive:
{
"kind": "youtube#videoListResponse",
"etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
"items": [
{
"id": "9bZkp7q19f0",
"kind": "youtube#video",
"etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
"contentDetails": {
"duration": "PT4M13S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": true,
"regionRestriction": {
"blocked": [
"DE"
]
}
}
}
]
}
Despite encountering similar issues before, my efforts remain unsuccessful in rectifying the problem.
Upon running the code, the console logs undefined, and the resultant output displays [Object object], which was anticipated.
Although resources like the Youtube Video Duration API v3 exist, they haven't provided solutions to my specific issue.
Your insights into why the code isn't producing the desired outcome would be greatly valued!
Thank you!
- Noah