I'm trying to automate the collection of phone numbers from an API into a Google Sheet with app script. I can get the data and place it in an array with the following code:
const options = { method: 'GET', headers: { Authorization: 'Bearer XXXXXXXXXXXXXXX', Accept: 'Application/JSON', } }; var serviceUrl = "dummyurl.com/?params"; var data=UrlFetchApp.fetch(serviceUrl, options); if(data.getResponseCode() == 200) { var response = JSON.parse(data.getContentText()); if (response !== null){ var keys = Object.keys(response.call).length; var phoneArray = []; for(i = 0; i < keys; i++) { phoneArray.push(response.call[i].caller.caller_id); } This works as expected - it grabs yesterday's caller ID values from a particular marketing campaign from my API. Next, I want to import this data into a column in my spreadsheet. To do this, I use the setValues method like so:
Logger.log(phoneArray); var arrayWrapper = []; arrayWrapper.push(phoneArray); Logger.log(arrayWrapper); for(i = 0; i < keys; i++) { var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var cell = sheet.getRange("A8"); cell.setValues(arrayWrapper); } } } } I am aware that I need my array length to equal the length of the selected range of cells in my sheet. However, I get conflicting errors depending on the length I set for my getRange method. If I set it to a single cell, as you see above, the error I get is:
The number of columns in the data does not match the number of columns in the range. The data has 8 but the range has 1.
However, if I set the length of my range to 8 (or any value except 1), I get the error:
The number of columns in the data does not match the number of columns in the range. The data has 1 but the range has 8.
As you see, the error swaps values. Now I have the appropriate number of columns in the range, but my script only finds 1 cell of data. When I check the log, I see that my 2D array looks normal in both cases - 8 phone numbers in an array wrapped in another array.
What is causing this error? I cannot find reference to similar errors on SO or elsewhere.
Also, please note that I'm aware this code is a little wonky (weird variables and two for loops where one would do). I've been troubleshooting this for a couple hours and was originally using setValue instead of setValues. While trying to debug it, things got split up and moved around a lot.