Google apps script 在google脚本中循环JSON响应

Google apps script 在google脚本中循环JSON响应,google-apps-script,Google Apps Script,我们正在尝试解决如何循环通过JSON响应 我们已经成功地调用了我们的第三方数据库的API,并提取了第一行(标题),但需要循环遍历所有行,然后将它们复制到一个GoogleSheets 有什么想法吗?没有太多关于您正在接收的JSON中包含哪些信息或您将如何处理这些信息的信息,因此以下是我的一般回答: 接收到完整的JSON数据后,可以使用JSON.parse(jsonString)将其转换为对象,其中jsonString是从API接收到的数据。更多关于这个 如果行值存储在数组中,则可以使用forEac

我们正在尝试解决如何循环通过JSON响应

我们已经成功地调用了我们的第三方数据库的API,并提取了第一行(标题),但需要循环遍历所有行,然后将它们复制到一个GoogleSheets


有什么想法吗?

没有太多关于您正在接收的JSON中包含哪些信息或您将如何处理这些信息的信息,因此以下是我的一般回答:

接收到完整的JSON数据后,可以使用
JSON.parse(jsonString)
将其转换为对象,其中jsonString是从API接收到的数据。更多关于这个

如果行值存储在数组中,则可以使用
forEach()
方法轻松循环它们。更多关于这个。下面是示例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);

  });
}

如果您有任何问题,请随时提问。

感谢@Christian4561的回复,抱歉花了这么长时间才感谢您的帮助,我为此撞到了墙,不得不走开重新组织!我在这里有一些帮助,我相信他们会很好地利用你的评论。