Youtube Video Duration API v3 [closed]

2020-08-02 05:55发布

问题:

Hey guys i have a little problem with the api v3 of youtube.

Question is, if the json have this structure

{
 "kind": "youtube#videoListResponse",
 "etag": "\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/1jshwBhrF6O49W3oUmNF7rmkgAQ\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#video",
   "etag": "\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/Zji9LPuiDCpb4GjgPpzdGgf85ws\"",
   "id": "3wFq1-pK05o",
   "contentDetails": {
    "duration": "PT1M1S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "true",
    "licensedContent": true
   }
  }
 ]
}

And i want get the video duration like this ?

$.getJSON( "https://www.googleapis.com/youtube/v3/videos?id=XXXX&key=XXXXX&part=contentDetails", function( json ) {
  document.write( "JSON Data: " + json["items"]["contentDetails"]["duration"] );
 }); 

But it doesn't work! I do not understand what's wrong. Please help me before I go crazy.

回答1:

Try this:

var json = {
    "kind": "youtube#videoListResponse",
    "etag": "\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/1jshwBhrF6O49W3oUmNF7rmkgAQ\"",
    "pageInfo": {
        "totalResults": 1,
        "resultsPerPage": 1
    },
    "items": [{
        "kind": "youtube#video",
        "etag": "\"tbWC5XrSXxe1WOAx6MK9z4hHSU8/Zji9LPuiDCpb4GjgPpzdGgf85ws\"",
        "id": "3wFq1-pK05o",
        "contentDetails": {
            "duration": "PT1M1S",
            "dimension": "2d",
            "definition": "hd",
            "caption": "true",
            "licensedContent": true
        }
    }]
}
console.log(json.items[0].contentDetails.duration);