我是Youtube Analytics Api
的新用户,我正在Google中关注 this guide ,使用Google Apps Script
在Google工作表中保存我的分析报告。每次我运行脚本时,都会出现这样的错误,
TypeError:无法从undefined中读取属性“length”。
这是代码,
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);
}
我没有编辑指南中的任何代码。正好遵循给出的内容。我怎样才能摆脱这个错误?急需这个帮助!感谢。
答案 0 :(得分:0)
就像错误说// Expire at the time indicated by the createdAt field
article.index({ createdAt: 1 }, { expireAfterSeconds : 10 });
未定义一样。这是因为没有为该查询返回数据。
来自https://developers.google.com/youtube/analytics/v1/reference/reports/query#response
的文档如果没有可用于给定查询的数据,则响应中将省略rows元素。