如何使用 javascript 将 json 数据写入 google 工作表

2024-01-08

我正在尝试使用 javascript 将 json 数据渲染到 google 工作表。

我尝试搜索大量文档,并且已经尝试了几个小时。我确实在工作表中输入了一行数据,但我需要在正确的行和列中渲染整个 json 数据集

function renderJSON() {
  /* This function collects JSON data from a specified endpoint
  and renders the data to a spreadsheet */

  // Fetch JSON data from the endpoint
  var url = 'http://dummy.restapiexample.com/api/v1/employees';
  var response = UrlFetchApp.fetch(url);     // Get the JSON data
  var object = JSON.parse(response.getContentText());
  //Logger.log(response);

  // Define an array of all object keys
  var rows = []; // Declare an empty array
  rows.push(object);
  var headerRow = Object.keys(rows);

  // Define an array of all object values
  var rows = headerRow.map(function(key){return rows [key]});

  // Define the contents of the range
  var contents = [
    headerRow,
    rows
    ];

  // Select the range and set its values
  var ss = SpreadsheetApp.getActive();
  var rng = ss.getActiveSheet().getRange(1, 1, contents.length, 
  headerRow.length)
  var i;
  for (i = contents[0]; i < contents.length; i++) {
    rng.setValues([i]);
  }
}

我希望整个 json 数据对于 Google 工作表来说是完美的格式,具有正确的标题并且所有内容都在正确的列中对齐。目前没有输出到工作表。


这个修改怎么样?在此修改中,首先从第一个元素检索标头值。并且从标头中检索值。然后,添加标题的值将被放入活动工作表中。

修改后的脚本:

function renderJSON() {
  var url = 'http://dummy.restapiexample.com/api/v1/employees';
  var response = UrlFetchApp.fetch(url);
  var object = JSON.parse(response.getContentText());

  var headers = Object.keys(object[0]);
  var values = object.map(function(e) {return headers.map(function(f) {return e[f]})});
  values.unshift(headers);
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}

如果我误解了你的问题并且这不是你想要的结果,我深表歉意。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 javascript 将 json 数据写入 google 工作表 的相关文章

随机推荐