循环 sheet 为 API POST 创建 JSON key-value 对

Loop though sheet to create JSON key-value pairs for API POST

我正在尝试编写一个 POST 方法 Google Apps 脚本(对于那些四处摸索尝试学习的人来说,这是一个相当大的成就)并且已经实现了我的目标的第一步这是一个有效的初始脚本 - 因为它运行并在 Zendesk 中创建一个字段,前提是我 'hard code'/明确地在脚本中写入 key-value 对(如下所示)。
我现在一直在尝试做的是遍历 Sheet 中的行以获得 key-value 配对和 POST(?) 每个 row/entry 从而允许我创建只需在 sheet.

中输入数据即可创建多个字段

我确定这将是一个 for 循环,但我在尝试真正弄明白时遇到了困难,希望这里有人能提供帮助。

我的数据在 Sheet 列 A:B 中(属性是类型和标题)是否有意义?我很沮丧,因为我只知道足以让我继续前进,但不知道如何完成它:-(

function CreateField2(){
  var sheet = SpreadsheetApp.getActiveSheet(); // data i want to use is here in columns A:B (type, text) - this will be expanded to other attributes eventually
//this is my data explicitly called out which works fine
  var data = {"ticket_field": {
    "type": "text", "title": "Age"}
  };      
//how do i take the values from my sheet and use them here?

  var url = 'https://url.com/api/v2/ticket_fields';
  var user = 'myaddress@somewhere.com/token';
  var pwd = 'myAPItokenHere';
  var options = {
      'method' : 'post',
      'headers': {
        'Authorization': "Basic " + Utilities.base64Encode(user + ':' + pwd)
      },
      'payload' : JSON.stringify(data),
      'contentType': 'application/json',
      'muteHttpExceptions': true
  };
  UrlFetchApp.fetch(url, options);
}

我在 sheet 中的数据将如下所示:

更新:以下关于 objects 与 objects 数组的评论。我想我真正需要做的是改变循环,以便它为每次迭代运行 post 方法?添加了以下内容:

    // Can i change the array of objects into separate objects?
const things = [
  data // this is the data gathered using either of the proposed methods
];
const filteredArr = things.reduce((thing, current) => {
  const x = thing.find(item => item.place === current.place);
  if (!x) {
    return thing.concat([current]);
  } else {
    return thing;
  }
}, []);
console.log(filteredArr)
// End of newly added code
//Note:  Not sure this is the right approach, i think i might need to to iterate over and perform the post function for each one?

替换为:-

var sheet = SpreadsheetApp.getActiveSheet(); // data i want to use is here in columns A:B (type, text) - this will be expanded to other attributes eventually
//this is my data explicitly called out which works fine
  var data = {"ticket_field": {
    "type": "text", "title": "Age"}
  };      

有了这个:-

  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const ssSource = ss.getSheetByName('Sheet1')
  const dataRange = ssSource.getDataRange().getValues();    
  var result = [];
  var head = dataRange[0]; // Getting Head Row
  var cols = head.length;
  var row = [];
  for (var i = 1; i < dataRange.length; i++)
  {
    row = dataRange[i]; // Getting data Rows
    var obj = {}; // Clearing Object
    for (var col = 0; col < cols; col++) 
    {
      obj[head[col]] = row[col];  // Assigning values to Keys  
    }
    result.push(obj);  // Pushing Object
  } 
  const data = JSON.stringify({ "ticket_field" : result}).replace(/[[\]]/g, '')

您可以在选项参数

中删除JSON.stringify

参考:

Array

Replace

尝试

function table2json() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YourSheetName');
  var [headers, ...rows] = sheet.getDataRange().getValues();
  var data = {}
  var items = []
  rows.forEach(function(r) {
    var obj={}
    r.forEach(function (c, j) {
      obj[headers[j]] = c
    })
    items.push(obj)
  })
  data['ticket_field'] = items
  Logger.log(JSON.stringify(data))
}

你会得到

{"ticket_field":[{"type":"text","title":"Summary"},{"type":"Multi-line text","title":"Description"},{"type":"Drop-down list","title":"Choose a thing"}, ... ]}

谢谢你们;经过几个小时或深思熟虑(Googling/trial 和错误)后,我使用以下代码工作:

function CreateFields(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
 var [headers, ...rows] = sheet.getDataRange().getValues();
 var data = {}
 var items = []
 rows.forEach(function(r) {
   var obj={}
   r.forEach(function (c, j) {
     obj[headers[j]] = c
   })
    var data = {}//moved
   data['ticket_field'] = obj // moved this inside your loop
   items.push(data) // pushed the object into the items array
 })
 
 Logger.log(JSON.stringify(items))
 
 items.forEach(function(i) {   // added this to loop over objects in items
 var url = 'https://urlhere.com/api/v2/ticket_fields';
 var user = 'myemailaddress/token';
 var pwd = 'mytokenhere';
 var options = {
     'method' : 'post',
     'headers': {
       'Authorization': "Basic " + Utilities.base64Encode(user + ':' + pwd)
     },
     'payload' : JSON.stringify(i),
     'contentType': 'application/json',
     'muteHttpExceptions': true
 };
 UrlFetchApp.fetch(url, options);
 Logger.log(i)
})
}