gpt4 book ai didi

google-apps-script - 在谷歌脚本中循环 JSON 响应

转载 作者:行者123 更新时间:2023-12-04 03:11:21 24 4
gpt4 key购买 nike

我们正在努力研究如何遍历 JSON 响应。

我们已经设法调用我们的 3rd 方数据库的 API 并拉出第一行(标题),但需要遍历所有行,然后将它们复制到 Google 表格中。

有任何想法吗?

最佳答案

关于您收到的 JSON 中有哪些信息或您将如何处理它,没有太多信息,所以这是我的一般答案:

收到完整的 JSON 数据后,您可以使用 JSON.parse( jsonString ) 将其转换为对象。其中 jsonString 是您从 API 收到的数据。更多相关信息 here .

如果您的行值存储在数组中,您可以使用 forEach() 轻松地遍历它们。方法。更多相关信息 here .下面是示例 JSON 数据和一个解析它的函数。

示例数据

{
"name": "Example Data",
"rows": [
{
"string": "I'm a string",
"number": 14
},
{
"string": "Chicago",
"number": 36
}
]
}

示例解析函数
function handleJsonResponse(data) {
//Parse response and get sheet
var response = JSON.parse(data);
var spreadsheet= SpreadsheetApp.getActive().getSheetByName(response.name);
if (spreadsheet === null) {
//Error here
}

//Loop through data and add it to spreadsheet
response.rows.forEach(function( row, index ) {
//This function will be executed for every row in the rows array

//Set the index of the row to the first column in the sheet
//2 is added to the index for the row number because index starts at 0 and we want to start adding data at row 2
spreadsheet.getRange(index + 2, 1).setValue(index);

//Set the value of string to the second column
spreadsheet.getRange(index + 2, 2).setValue(row.string);

//Set the value of number to the third column
spreadsheet.getRange(index + 2, 3).setValue(row.number);

});
}

如果您有任何问题随时问。

关于google-apps-script - 在谷歌脚本中循环 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45021158/

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