gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:13:13 25 4
gpt4 key购买 nike

我正在尝试使用 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 工作表来说是完美的格式,具有正确的标题并且所有内容都在正确的列中对齐。目前没有输出到工作表。

最佳答案

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

修改后的脚本:

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);
}

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

关于json - 如何使用 javascript 将 json 数据写入 google 工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58141901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com