【发布时间】:2019-09-27 22:26:44
【问题描述】:
我正在尝试使用 javascript 将 json 数据呈现到谷歌表格。
我已经尝试搜索大量文档,并且已经尝试了几个小时。我的工作表中确实有一行数据,但我需要将整个 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 工作表具有完美的格式。目前没有输出到工作表。
【问题讨论】:
-
您确认
contents包含您期望的内容了吗? -
您是否收到错误消息?还是它没有错误地完成,但看起来不像您预期的那样?
-
数据中的行数与范围内的行数不匹配。数据有 1 但范围有 2。
-
contents 包含使用 Logging.log(contents) 的 json 数据
-
我想我可能会看到问题所在。
contents中只有 2 项:标题和行,行本身就是一个对象。因此,通过遍历contents的内容,您将放入标题行 - 然后是代表所有其他行的 JSON 数据块。
标签: json google-apps-script google-sheets