0

我是新手Youtube Analytics Api,我正在按照google 中的本指南Google Apps Script使用. 每次我运行脚本时,我都会收到这样的错误,

TypeError:无法从未定义中读取属性“长度”。

这是代码,

  function spreadsheetAnalytics() {
  // Get the channel ID
  var myChannels = YouTube.Channels.list('id', {mine: true});
  var channel = myChannels.items[0];
  var channelId = channel.id;
  // Set the dates for our report
  var today = new Date();
  var oneMonthAgo = new Date();
  oneMonthAgo.setMonth(today.getMonth() - 1);
  var todayFormatted = Utilities.formatDate(today, 'UTC', 'yyyy-MM-dd')
  var oneMonthAgoFormatted = Utilities.formatDate(oneMonthAgo, 'UTC', 'yyyy-MM-dd');

    var analyticsResponse = YouTubeAnalytics.Reports.query(
        'channel==' + channelId,
        oneMonthAgoFormatted,
        todayFormatted,
        'views,likes,dislikes,shares',
        {
          dimensions: 'day',
          sort: '-day'
        });

  var ssName = 'YouTube channel report ' + oneMonthAgoFormatted + ' - ' + todayFormatted;
  var numRows = analyticsResponse.rows.length;  // ERROR IN THIS LINE
  var numCols = analyticsResponse.columnHeaders.length;

  var ssNew = SpreadsheetApp.create(ssName, numRows + 1, numCols);
  var sheet = ssNew.getSheets()[0];

  // Get the range for the title columns
  // Remember, spreadsheets are 1-indexed, whereas arrays are 0-indexed
  var headersRange = sheet.getRange(1, 1, 1, numCols);
  var headers = [];

  // These column headers will correspond with the metrics requested
  // in the initial call: views, likes, dislikes, shares
  for(var i in analyticsResponse.columnHeaders) {
    var columnHeader = analyticsResponse.columnHeaders[i];
    var columnName = columnHeader.name;
    headers[i] = columnName;
  }

  headersRange.setValues([headers]);

  headersRange.setFontWeight('bold');
  sheet.setFrozenRows(1);

  var dataRange = sheet.getRange(2, 1, numRows, numCols);
  dataRange.setValues(analyticsResponse.rows);

  var dateHeaders = sheet.getRange(1, 1, numRows, 1);
  dateHeaders.setFontWeight('bold');
  sheet.setFrozenColumns(1);

  var range = sheet.getRange(1, 1, numRows, numCols);
  var chart = sheet.newChart()
                   .asColumnChart()
                   .setStacked()
                   .addRange(range)
                   .setPosition(4, 2, 10, 10)
                   .build();
  sheet.insertChart(chart);
}

我没有编辑指南中的任何代码。只需遵循给出的内容即可。我怎样才能摆脱这个错误?

4

1 回答 1

0

就像错误所说rows的未定义一样。这是因为没有为该查询返回数据。

从以下文档中找到: https ://developers.google.com/youtube/analytics/v1/reference/reports/query#response

如果没有可用于给定查询的数据,则将从响应中省略 rows 元素。

于 2016-03-28T20:03:33.030 回答