如何使用javascript将json数据写入google工作表
我正在尝试使用javascript将json数据呈现到google工作表中 我已经尝试过搜索大量的文档,我已经尝试了几个小时。我的工作表中有一行数据,但我需要以正确的行和列呈现整个json数据集如何使用javascript将json数据写入google工作表,json,google-apps-script,google-sheets,Json,Google Apps Script,Google Sheets,我正在尝试使用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
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工作表中,标题正确,所有内容都在正确的列中对齐。当前没有输出到工作表。此修改如何?在这个修改中,首先从第一个元素检索头值。并从标题中检索值。然后,将添加标题的值放入活动工作表中 修改脚本:
如果我误解了您的问题,并且这不是您想要的结果,我很抱歉。您是否已验证内容是否包含您期望的内容?是否收到错误消息?或者它完成时没有错误,但看起来不像您期望的那样?数据中的行数与范围中的行数不匹配。数据有1,但范围有2。contents包含使用Logging.logcontent的json数据。我想我可能看到了问题。内容中只有两项:标题和行,行本身就是一个对象。因此,通过迭代内容的内容,您将放入标题行,然后是一个代表所有其他行的JSON blob。谢谢,没有进一步修改就成功了:@j86h谢谢您的回复。我很高兴你的问题解决了。
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);
}