Import list of contact groups in GAS - google-contacts-api

I can't find anything related in Stack Overflow on this.
I'm trying to post a list of my google contact group names and id's into F16:G.
The code I'm using keeps saying: "Cannot convert Array to Object[][]. (line 39, file "email")"
Please help! I'm not good at arrays! An explanation of what I'm doing wrong would be awesome as well!
function importContactGroups() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheetByName("Load Email");
var dataRow = dataSheet.getRange("F16:F");
var groupArray = new Array();
//var groups = Browser.inputBox("Enter the name of your Gmail Contacts group here:");
//var mySheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
//var myContacts = ContactsApp.findContactGroup(groupName).getContacts();
var groups = ContactsApp.getContactGroups();
for (var i = 0; i < groups.length; i++) {
var groupNames = groupArray.push(groups[i].getName());
};
dataSheet.getRange(16, 4, groupArray.length, 5).setValues(groupArray);
// for (i=0; i < myContacts.length; i++) {
// var myContact = [[myContacts[i].getFullName(), myContacts[i].getPrimaryEmail(), "Pending"]];
//mySheet.getRange(i+2, 1,1,3).setValues(myContact);
//}
//Browser.msgBox("You have successfully imported " + myContacts.length + " contacts from Gmail. Please proceed to Step 3.");
}

Tried your code on my end and this is the line that causes the error.
dataSheet.getRange(16, 4, groupArray.length, 5).setValues(groupArray);
First, you dont have to use this kind of array in JS:
var groupArray = new Array();
This type of array will work fine
var groupArray = ["a","b","c"];
Now to address your issue with .setValues, follow the given format from the docs:
// The size of the two-dimensional array must match the size of the range.
var values = [
[ "2.000", "1,000,000", "$2.99" ]
];
So to fix your code you need to have a 2D array format for "groupArray". Here's a working concept demo of your code, hope you be able to apply it on your situation:
function importContactGroups() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheetByName("Sheet1");
var dataRow = dataSheet.getRange("F16:F");
var groupArray = [
[ "apple", "banana", "orange" ,"jackfruit","kiwi" ]
];
dataSheet.getRange(1, 4, groupArray.length, 5).setValues(groupArray);
}
Output:

Related

How to create a valid 2D array that Google Apps Script Form will accept for Checkbox grid question response

I am getting values from a sheet and needing to convert the values into a 2D array that will then be accepted by .createResponse() of Google Forms. In the spreadsheet, the values for cell[0] = Paris, NYC and cell[1] = LA. I have tried this function:
function testFunction1() {
const ss = SpreadsheetApp.getActiveSheet();
const form = FormApp.openByUrl(ss.getFormUrl());
var arr = [];
for(i = 0; i<2; i++){
var cell = ss.getRange(2,i+2).getValue();
cell = cell.split(',');
arr.push(cell);
}
var newRes = form
.getItems()[0]
.asCheckboxGridItem()
.createResponse(arr);
form.createResponse().withItemResponse(newRes).submit();
}
When I split each cell, I get:
split cell[0] = ['Paris', 'NYC']
split cell[1] = ['LA']
After pushing the items into arr, I get:
arr = [ ['Paris', 'NYC'], ['LA'] ]
This looks like a 2D array but then .createResponse(arr) gives the error of "Exception: Invalid response submitted to checkbox grid question."
If I manually enter [ ['Paris', 'NYC'], ['LA'] ] into the .createResponse like this:
function testFunction2() {
const ss = SpreadsheetApp.getActiveSheet();
const form = FormApp.openByUrl(ss.getFormUrl());
var newRes = form
.getItems()[0]
.asCheckboxGridItem()
.createResponse([ ['Paris','NYC'], ['LA'] ]);
form.createResponse().withItemResponse(newRes).submit();
}
then there is no error and the response is added to the Form correctly.
I have also tried:
function testFunction1() {
const ss = SpreadsheetApp.getActiveSheet();
const form = FormApp.openByUrl(ss.getFormUrl());
var arr = [[]];
for(i = 0; i<2; i++){
var cell = ss.getRange(2,i+2).getValue();
cell = cell.split(',');
arr[0][i] = cell;
console.log(cell);
}
var cell = arr;
console.log(cell[0]);
var newRes = form
.getItems()[0]
.asCheckboxGridItem()
.createResponse(cell[0]);
form.createResponse().withItemResponse(newRes).submit();
}
This throws the error of "Exception: Invalid response submitted to checkbox grid question." at the .createResponse(cell[0]).
Also if the .createResponse(cell[0]) is changed to .createResponse(cell), then the following error is received, "Exception: The parameters (number[]) don't match the method signature for FormApp.CheckboxGridItem.createResponse."
I also used typeof of the manually typed item, cell values, and resulting arrays and they all come up as object. What am I doing wrong?
Adam
From the situation that .createResponse([ ['Paris','NYC'], ['LA'] ]); works and cell[0] = Paris, NYC and cell[1] = LA in your question, I'm worried that each value of arr might have a space. This is just my guess. So in your script, how about the following modification?
From:
cell = cell.split(',');
To:
cell = cell.split(',').map(e => e.trim());
or,
From:
var arr = [];
for(i = 0; i<2; i++){
var cell = ss.getRange(2,i+2).getValue();
cell = cell.split(',');
arr.push(cell);
}
To:
var arr = ss.getRange(2, 2, 1, 2).getValues()[0].map(c => c.split(",").map(e => e.trim()));
References:
map()
trim()

TypeError: Cannot read property '0' of undefined (Google Sheets / App Script)

I would like to know what I need to adjust in the script so that the results appear in the spreadsheet:
TypeError: Cannot read property '0' of undefined (line 7)
function Cartola() {
var url = "https://api.cartolafc.globo.com/mercado/destaques";
var response = UrlFetchApp.fetch(url);
var data = response.getContentText();
var result = JSON.parse(data);
var apelido = result.Atleta[0].apelido;
var foto = result.Atleta[0].foto;
var clube_nome = result.Atleta[0].clube_nome;
var posição = result.Atleta[0].posicao;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear()
var headerRow = ['apelido','foto','clube_nome','posição'];
sheet.appendRow(headerRow);
for(var i=0;i<result[0].Atleta;i++){
var row = [result.Atleta[i].apelido,result.Atleta[i].foto,result.Atleta[i].clube_nome,result.Atleta[i].posicao];
SpreadsheetApp.getActiveSheet().appendRow(row);
}
}
data is an array, so you need to access the element first:
var apelido = result[0].Atleta.apelido;
I think you're trying to print every player to spreadsheet, but what you've written is only looking at one of the players. Please first look at the data returned by the API and understand its structure. Looks something like this:
[
{
"Atleta": {
"atleta_id": 68952,
"nome": "Mário Sérgio Santos Costa",
"apelido": "Marinho",
"foto": "https://s.glbimg.com/es/sde/f/2019/05/30/cd8a7f9b0744e105efa0a0c572d37d6f_FORMATO.png",
"preco_editorial": 5
},
"escalacoes": 996124,
"clube": "SAN",
"clube_nome": "Santos",
"clube_id": 277,
"escudo_clube": "https://s.glbimg.com/es/sde/f/organizacoes/2014/04/14/santos_60x60.png",
"posicao": "Atacante",
"posicao_abreviacao": "ATA"
}
]
Once you understand the data, then consider this modified script, which uses batch operations to run much more quickly.
function Cartola() {
var url = 'https://api.cartolafc.globo.com/mercado/destaques';
var response = UrlFetchApp.fetch(url);
var results = JSON.parse(response.getContentText());
var table = [['apelido','foto','clube_nome','posição']];
for (var i = 0; i < results.length; i++) {
var r = results[i];
var apelido = r.Atleta.apelido;
var foto = r.Atleta.foto;
var clube_nome = r.clube_nome;
var posição = r.posicao;
table.push([apelido, foto, clube_nome, posição]);
}
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear().getRange(1, 1, table.length, table[0].length).setValues(table);
}

Get data from array in nested json using Google Script

I need to fix a Google Script I've been working on. Basically, I have a json https://www.instagram.com/nike/?__a=1 that returns basic info about Nike's account on instagram. I have no problem retrieving data from objects such as "biography". But, when I try to retrieve nested objects (arrays) I'm doing something wrong because the results arrive duplicated (see attachment). Can anyone help me figure out what I'm doing wrong?
// the name of the sheet within your document
var sheetName = "Sheet1";
// the name of the Instagram account you want the follower count for
var instagramAccountName = "nike";
function insert() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(this.sheetName);
var followers = [];
var followers = captionArray(this.instagramAccountName);
for(var i = 0 ; i < 3; i++) {
sheet.appendRow([Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"), followers]);
};
}
function captionArray(username) {
var i = 0;
for(var i = 0; i < 3; i++) {
var url = "https://www.instagram.com/" + username + "/?__a=1";
var response = UrlFetchApp.fetch(url).getContentText();
var caption = [];
var caption = JSON.parse(response).graphql.user.edge_owner_to_timeline_media.edges[i].node.edge_media_to_caption.edges[i].node.text;
return caption;
};
}
I think this is causing problems:
You're using the same index (i) for both arrays, but the second have only one element.
You just need to do one request.
This code works for me:
function captionArray(username) {
var captions = [];
var url = "https://www.instagram.com/nike/?__a=1";
var response = UrlFetchApp.fetch(url).getContentText();
var edges = JSON.parse(response).graphql.user.edge_owner_to_timeline_media.edges;
for(var i = 0, limit = edges.length; i < limit; i++) {
captions.push(edges[i].node.edge_media_to_caption.edges[0].node.text);
}
return captions;
}

Parse JSON formatted result of HTTP request into columns

Google Apps Script to pull data from API. I'd like to parse out the information according to the relevant headers.
function Fraud2() {
var ret = "no value";
var response = UrlFetchApp.fetch("https://fraudshield.24metrics.com/api/v1/reports/fraud.json?tracker_id=905&group[]=sub_id&group[]=partner&date_start=2018-01-18&date_end=2018-01-18&timezone=UTC&user_id=XXX&api_token=XXX",{muteHttpExceptions:true})
var user_id = "XXX";
var api_token = "XXX";
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([response]);
}
The return is pushed into one single cell like so:
{"results":[{"tracker_id":905,"conversion":7883,"click":0,"goal":0,"approved":6511,"rejected":1372,"tracker":"Tatoo
Integration","conversion_rate":"N\/A"},{"tracker_id":906,"conversion":1868,"click":0,"goal":0,"approved":1682,"rejected":186,"tracker":"Aise
Integration","conversion_rate":"N\/A"},{"tracker_id":933,"conversion":413,"click":0,"goal":0,"rejected":290,"approved":123,"tracker":"Tatoo
Invalids Integration","conversion_rate":"N\/A"}]}
I tried this without success.
How can I get the results arranged neatly into columns?
As Hink said, you need to convert the object to an array first.
Hinks solution will work fine but below is a combination of the code you tried to use in your post.
function Fraud2() {
var ss = SpreadsheetApp.getActiveSheet();
var ret = "no value";
var response = UrlFetchApp.fetch("https://fraudshield.24metrics.com/api/v1/reports/fraud.json?tracker_id=905&group[]=sub_id&group[]=partner&date_start=2018-01-18&date_end=2018-01-18&timezone=UTC&user_id=XXX&api_token=XXX",{muteHttpExceptions:true})
var user_id = "XXX";
var api_token = "XXX";
var out=JSON.stringify(response.results);
out=JSON.parse(out)
var title = [];
for (var i in out[0]) {
title.push(i);
}
var res = [];
res.push(title);
for (var i in out) {
var values = [];
for (var j in out[i]) {
values.push(out[i][j]);
}
res.push(values);
}
ss.getRange(1, 1, res.length, res[0].length).setValues(res);
};
You need to convert the response object into an array and append the array:
for (var i = 0; i < response.results.length; i++){
var current = response.results[i];
var myArray = [current.tracker_id, current.conversion, current.click, current.goal, current.approved, current.rejected, current.tracker,current.conversion_rate];
sheet.appendRow(myArray);
}

google script - json into google sheet

I'm new to scripting and I would appreciate your help. I do apologize for what might be a simple question.
What I have is an api that gives json:
[{"id":"xyz","name":"xy"},
{"id":"zyx","name":"yx"}]
The above continues lets say for another 100 ids.
What I want is to put that into the cells in google spreadsheet.
What I have currently is:
var ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var rr = sh.getRange(3,2,100,5);
var id = "www.xyz.com/api";
var jsonData = UrlFetchApp.fetch(id);
var jsonString = jsonData.getContentText();
var idsearch = JSON.parse(jsonString);
for (var i = 1; i < idsearch.count; i++)
{
var cellid = rr.getCell(i,1);
eventid.setValue(idsearch.results[i].id);
var cellname = rr.getCell(i,2);
eventname.setValue(idsearch.results[i].name);
}
When I run the script, nothing happens. It doesnt return anything.
Did I make a mistake in the script? Is there an easier way to put all the json result into google sheet? Is there an example where I can look at to learn about what I'm trying to do?
Thank you very much.
I hope this simple code might help you.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getActiveSheet();
var dataSet = [
{"id":"xyz","name":"xy"},
{"id":"zyx","name":"yx"}
];
var rows = [],
data;
for (i = 0; i < dataSet.length; i++) {
data = dataSet[i];
rows.push([data.id, data.name]);
}
dataRange = sheet.getRange(1, 1, rows.length, 2);
dataRange.setValues(rows);
}
You might also want to inspect the example here (it's based on ScriptDb but will work with any JSON array).
https://developers.google.com/apps-script/scriptdb#copy_a_database_to_a_new_sheet_in_a_spreadsheet