【问题标题】:TypeError: Cannot read property "contentDetails" from undefinedTypeError:无法从未定义中读取属性“contentDetails”
【发布时间】:2025-11-22 06:40:01
【问题描述】:

我正在尝试从一些播放列表中获取一些 youtube 视频 ID。循环开始,但最终我在主题行中看到了错误(在这一行:var videoID = jsonVideoListResult.items[j].contentDetails.videoId;)。

Logger 结果也在下面。我是 GAS 新手,非常感谢您的帮助!

[17-05-05 20:39:33:921 EDT] VideoListResult: [object Object]
[17-05-05 20:39:33:922 EDT] VideoID: _R-mvxYzOo8
[17-05-05 20:39:33:982 EDT] VideoListResult: [object Object]
[17-05-05 20:39:33:983 EDT] VideoID: -oqQxOv9HHM
[17-05-05 20:39:34:037 EDT] VideoListResult: [object Object]
[17-05-05 20:39:34:037 EDT] VideoID: WV_I9rvrzsY
[17-05-05 20:39:34:077 EDT] VideoListResult: [object Object]


//get each playlist in the array and get its video ids
  var videoIdArray = [];
  for (var j=0; j<playlists.length; j++) {

  var videoURLprefix = 'https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=50&playlistId=';
  var videoURLsuffix = '&fields=items%2FcontentDetails%2FvideoId&key=';
  var playListID = String;
      playListID = playlists[j];
      //Logger.log(playListID);

  var getVideo = UrlFetchApp.fetch(videoURLprefix + playListID + videoURLsuffix + apiKey);

  var jsonVideoListResult = [];
      jsonVideoListResult = JSON.parse(getVideo);
    Logger.log("VideoListResult: " + jsonVideoListResult);
  var videoID = jsonVideoListResult.items[j].contentDetails.videoId;
  Logger.log("VideoID: " + videoID);
  videoIdArray.push(videoID); 

  }

【问题讨论】:

    标签: google-apps-script


    【解决方案1】:

    api调用返回的item长度与播放列表长度不同。因此,此代码将需要有两个循环。一个用于您的播放列表数组,第二个用于 api 调用返回的项目数组(包含该特定播放列表中的视频列表)。

    像这样

    var videoIdArray = [];
      for (var j=0; j<playlists.length; j++) {    //First Loop to go through each playlist
    
      var videoURLprefix = 'https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=50&playlistId=';
      var videoURLsuffix = '&fields=items%2FcontentDetails%2FvideoId&key=';
      var playListID = String;
          playListID = playlists[j];
          //Logger.log(playListID);
    
      var getVideo = UrlFetchApp.fetch(videoURLprefix + playListID + videoURLsuffix + apiKey);
    
      var jsonVideoListResult = [];
          jsonVideoListResult = JSON.parse(getVideo);
        Logger.log("VideoListResult: " + jsonVideoListResult);
      for (var i = 0 ; i< jsonVideoListResult.items.length ; i++) {   // Second loop to ireate through the each video in the playlist as returned by the api. 
       var videoID = jsonVideoListResult.items[i].contentDetails.videoId;
       Logger.log("VideoID: " + videoID);
       videoIdArray.push(videoID); 
     }
    
     }
    

    希望有帮助!

    【讨论】:

    • 啊!这样做。非常感谢!
    最近更新 更多