json - 如何将 JSON 响应转换为表格中的表格
问题描述
我正在向 API 发送请求(在 Google 脚本中),我收到的响应是 JSON 文本,如下所示:
[{"id":26319355,"name":"1. WAW -FIRST SESION","calendar":"Glovers
Click&Collect","duration":30,"isSeries":false,"slots":90,"slotsAvailable"
:89,"color":"#E3DE7D","price":"0.00","category":"WAW","description":"",
"calendarID":2978881,"serviceGroupID":2978881,"appointmentTypeID":10104780,
"calendarTimezone":"Europe\/Madrid","time":"2019-06-01T12:00:00+0200",
"localeTime":"June 1, 2019 12:00"},
{"id":26466803,"name":"1. WAW -FIRST SESION","calendar":"Glovers
Click&Collect","duration":30,"isSeries":false,"slots":90,"slotsAvailable"
:89,"color":"#E3DE7D","price":"0.00","category":"WAW","description":"",
"calendarID":2978881,"serviceGroupID":2978881,"appointmentTypeID":10104780,
"calendarTimezone":"Europe\/Madrid","time":"2019-06-07T14:00:00+0200",
"localeTime":"June 7, 2019 14:00"},
我想将此响应作为表格粘贴到我的电子表格中。
我的脚本实际上是这样的(其中响应是我从 API 请求中得到的响应):
function CheckAv(row,acuityid,check,url,apiusername,apisecretkey,ss) {
var header = {
"contentType": "application/json",
"headers":{"Authorization" : " Basic " + Utilities.base64Encode(apiusername + ":" + apisecretkey)},
"method" : "GET"
}
muteHttpExceptions: true
var response = UrlFetchApp.fetch(url, header);
var data = JSON.parse(response.getContentText());
var text = response.getResponseCode();
Logger.log(text);
}
我认为这将非常容易,但我找不到解决方案。
解决方案
您可以使用以下代码循环浏览您的 JSON 结构并将每个键和值推送到指定的行。
json = [{your: "JSON", data: "goes"}, {in : "here"}]
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getActiveSheet();
var rows = [],
data;
for (i = 0; i < json.length; i++) {
for (j in json[i]) {
dataq = json[i][j];
Logger.log(dataq);
rows.push([j, dataq]);
}
dataRange = sheet.getRange(1, 1, rows.length, 2);
dataRange.setValues(rows);
}
推荐阅读
- python - 如何在python中识别函数和模块化代码?
- testng - 即使 testng 类中的方法抛出异常, ITestResult 也会返回状态成功
- javascript - 检查对象嵌套属性是否存在并返回其值
- resources - 当 URL 未出现在源代码中时,如何避免错误请求?
- html - 如何旋转外部div而不是内部内容
- php - 如何修复 'Illuminate \ Database \ Eloquent \ MassAssignmentException' 上的 _token 错误
- reactjs - React- Webpack 缩小代码并在开发环境中创建包。我想要 dev 中的所有未捆绑的文件,以便我可以调试
- java - ListView 不使用自定义视图更新大小
- xml - XML 文件输出失败
- python-3.x - 通过python将文件作为输入传递给shell脚本