在Google Apps脚本中,我通过OAuth2连接到服务。我得到一个JSON响应并用JSON.parse(response.getContentText());
解析它所以它记录如下:
{Results=[{Id=45364743, Description=null, Name=Math I , IsActive=true},
{Id=45364768, Description=null, Name=Math II, IsActive=true}]}
使用以下代码,我之前已采用JSON响应并将其成功写入Google表格。但是,这次FOR循环没有运行,因为dataSet
没有length
。我猜这是因为一切都嵌套在“结果”下。
function getService2() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName('Data');
var key = 'kjeu7hjf7873alkjhehjhfayuluoojsds'
var options = {
method: "get",
headers: {
Authorization: "Bearer " + key,
api_key: key,
}
}
var response = UrlFetchApp.fetch(URL, options);
var dataAll = JSON.parse(response.getContentText());
var dataSet = dataAll;
Logger.log(dataSet)
var rows = [],
data;
for (i = 0; i < dataSet.length; i++)
if ( dataSet.length > 0.0){
data = dataSet[i];
rows.push([data.Id, data.Name, data.IsActive ]); //your JSON entities here
dataRange = sheet.getRange(lastRow + 1, 1, rows.length , 2);
dataRange.setValues(rows);
}}
我如何确定解析的JSON响应(即“dataSet”)的长度来运行循环并写入工作表?
我注意到了一些错误并进行了编辑以修复它们。你的for
循环有问题。你在每次迭代时都写入了表格,这是不符合要求的。
function getService2() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName('Data');
var key = 'kjeu7hjf7873alkjhehjhfayuluoojsds';
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + key,
api_key: key
}
};
var response = UrlFetchApp.fetch(URL, options);
var dataAll = JSON.parse(response.getContentText());
var dataSet = dataAll.Results;
Logger.log(dataSet);
var rows = [],
data;
for (i = 0; i < dataSet.length; i++) {
data = dataSet[i];
rows.push([data.Id, data.Name, data.IsActive]); //your JSON entities here
}
sheet.getRange(lastRow + 1, 1, rows.length, 3).setValues(rows);
}