簡體   English   中英

google apps腳本json解析錯誤

[英]google apps script json parse error

我的腳本遇到了一個小問題。

我正在嘗試獲取json網址,並將json文件中的數據獲取到Google電子表格中。 以前,我在Spreadsheet中使用了= importData()函數。 但是,我注意到該函數有時不可靠,並返回#N / A。 我想創建一個腳本,可以計划在需要時運行該腳本。

代碼中某處肯定有錯誤? 你們能幫我嗎? 我得到的錯誤是:

范圍的坐標或尺寸無效。 (第25行,文件“代碼”)

這是指向Google電子表格文件的鏈接: https : //docs.google.com/spreadsheets/d/15xQy8GDyHRMZXBPcnmSLYUl6GSHZLpTkfhvYR7-BjvQ/edit?usp=sharing

在Sheet3上是= importData()函數的外觀示例。 以及我希望此自定義腳本的外觀如何。

function FetchUrl() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()

  var url = sheet[0].getRange(1, 2).getValue();
  var response = UrlFetchApp.fetch(url);
  var json = response.getContentText();
  var dataAll = JSON.parse(json);
  Logger.log(dataAll);
  var dataset = dataAll;

  var rows = [],
      data;

  for (i = 0; i < dataset.lenght; i++){
    data = dataset[i];
    rows.push([data.title, data.fields, data.values]);
  }
  dataRange = sheet[1].getRange(2, 1, rows.length, 3);
  dataRange.setValues(rows);

}

Logger.log輸出

[17-01-16 02:34:38:354 PST] {types=[1082, 20, 20, 20, 20, 20, 20, 20], type_names=[unknown, integer, integer, integer, integer, integer, integer, integer], values=[[2017-01-15, 3, 1, 3, 0, 2, 0, 0]], title=Course's all topics' starts yesterday: Get that job (en, -NG), fields=[date, findyourdreamjob, bethebestjobseeker, writethebestcv, findthebestjobs, getajobinterview, excelatjobinterviews, firstdaysonthejob]}

提前致謝!

如果在聲明了“ var數據集=”之后在某處添加以下代碼,則Logger.log('dataset.length ='+ dataset.length);

運行並檢查Logger.log時,發現dataset.length未定義。 (JSON.parse的輸出是一個對象,因此數據集是一個對象而不是數組)

因此,由於未定義長度,因此進一步深入腳本,for循環將運行零次。

因此您的行輸出仍為空數組[],因此仍然顯示錯誤消息(我想,但我不能確定這是唯一的原因)。

順便說一句,您拼寫的長度錯誤。 但這不會產生錯誤,因為跳過了循環(再次,我想是)。

下面的腳本按照表3給出結果,供您比較。

function FetchUrl2() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()

  var url = sheet[0].getRange(1, 2).getValue();
  var response = UrlFetchApp.fetch(url);
  var json = response.getContentText();
  var dataAll = JSON.parse(json);
  Logger.log(dataAll);  // inspecting through Logger.log shows dataAll is an object not an array.  So, in the lines below, the headers and values are extracted from this object and recreated into an array.

  var headers = dataAll.fields; 
  var values = dataAll.values[0]; 
  var output = [headers,values];
  Logger.log(output)
  var dataRange = sheet[1].getRange(2,1,output.length, output[0].length);
  dataRange.setValues(output);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM