如何使用应用程序脚本将json数组数据插入谷歌应用程序电子表格?

时间:2017-06-14 13:42:47

标签: google-apps-script google-sheets

我有两个方法,一个方法以JSON数组的形式返回数据。现在我想把这些数据写入谷歌应用程序脚本。怎么做?

使用下面的代码我得到

  

无法将数组转换为对象"错误

var noEpicListArray = new Array();

if(epicCount==0){
  var noEpicMetric = {
    "issueKey": "No Epic",
    "issueSummary": "NA",
    "epicEfficiency": "NA",
    "teamName": "NA",
    "firstPassInd": "NA",
    "secondPassInd": "NA",
    "thirdPassInd": "NA",
    "tooManyPassInd": "NA",
    "storyCountInsideEpic": "NA" 
}

noEpicListArray.push(noEpicMetric);
epicWiseEpicEfficiencySheet.getRange(2, 1, 1, 9).setValues(noEpicListArray); }

1 个答案:

答案 0 :(得分:0)

要将数据对象中的值附加到电子表格,请从数据对象中的每个键/值元素中提取值,将这些值放入数组中,然后将数据附加到现有数据的末尾。 JavaScript数据对象的结构为{"key":"value"}

function dataObjectToSpreadsheet(dataObject) {
  var dataArray,k,ss,sh;//define variables without assigning a value

  dataObject= {
    "issueKey": "No Epic For This Sprint",
    "issueSummary": "NA",
    "epicEfficiency": "NA",
    "teamName": "NA",
    "firstPassInd": "NA",
    "secondPassInd": "NA",
    "thirdPassInd": "NA",
    "tooManyPassInd": "NA",
    "storyCountInsideEpic": "NA" 
    } 

  if (typeof dataObject === 'string') {//If the object was stringified
    dataObject = JSON.parse(dataObject);//convert from string to object
  }

  ss = SpreadsheetApp.getActiveSpreadsheeet();
  sh = ss.getSheetByName('Put sheet tab name here');

  innerArray = [];//assign an empty array to the variable innerArray

  for (k in dataObject) {//Loop through all elements of the data object
    thisValue = dataObject[k];
    dataArray.push(thisValue);
  }

  sh.appendRow(dataArray);  
}