How to transform the JSON response into a table in sheets - json

I'm sending a request to an API (in a Google Scripts), and I'm getting the response as a JSON text that looks like this:
[{"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"},
I want to paste this response as a table in my spreadsheet.
My script actually looks like this (where response is the response I get from the API request):
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);
}
I assume it will be really easy but I can't find the solution.

You can cycle through your JSON structure and push each key and value to a specified row using the code below.
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);
}

Related

How to iterate for each cell in Google Sheet range with hyperlinks and send batch photos to Telegram?

For example, I have this range with 10 Drive hyperlinks to images:
This script already sends only one photo (F1) to a group via Telegram Bot, but I need to iterate for each cell in this range to send every uploaded images (via Google Forms, max. 10), but it could be only one or ten pictures, so I need to stop the iteration if is an empty cell like N1 and O1.
photo_url = "DRIVE_URL";
id = "GROUP_ID";
sendPhoto(id,photo_url)
function sendPhoto(id,photo_url) {
var API_TOKEN = "BOT_TOKEN";
var payload = {
'method': 'sendPhoto',
'chat_id': String(id),
'photo': photo_url,
'caption': "Foto 1"
}
var data = {
"method": "post",
"payload": payload,
'muteHttpExceptions':true,
}
//var response =
UrlFetchApp.fetch('https://api.telegram.org/bot' + API_TOKEN + '/', data);
//Logger.log(response);
}
*Plus, is it the same process to change the name or caption of every image? making this code dynamic:
'caption': "Foto 1"
'caption': "Foto 2"
'caption': "Foto 3" //...etc., until max. 10, sometimes is empty.
*Edited, this is the working code only to find data (URL photos in a Drive) inside a range of 10 cells (F2:O2):
function loopImage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("AWESOME");
var vals =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("AWESOME")
.getRange(2 +":"+ 2)
.getValues()[0],
lastColNum = vals.length
;
while(!vals.pop())
{ --lastColNum; }
var range = sh.getRange(2, 6, 2, lastColNum-5); //The command will automatically adjust the range based on the last column of the F2:O2 range.
var data = range.getValues();
var photoArr = [];
for(var i=0; i<data[0].length; i++){
photoArr.push({"type": "photo", "media": data[0][i], "caption": "Foto "+(i+1)})
}
if(photoArr.length > 0){
sendPhoto(JSON.stringify(photoArr));
}
}
function sendPhoto(photoArray) {
id = "GROUP_TOKEN";
var API_TOKEN = "BOT_API";
var payload = {
'method': 'sendMediaGroup',
'chat_id': String(id),
'media': photoArray,
}
var data = {
"method": "post",
"payload": payload,
"muteHttpExceptions":true,
}
var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + API_TOKEN + '/', data);
Logger.log(response);
}
The script below will loop through the first row of Sheet starting from column F up to the last column with data, creates an array of object of InputMediaPhoto, and send the array to sendPhotoArray function to send it to a Telegram group chat.
Code:
function loopImage() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Enter Sheet Name Here");
var range = sh.getRange(1, 6, 1, sh.getLastColumn()-5); //The command will automatically adjust the range based on the last column of the first row.
var data = range.getValues();
var photoArr = [];
for(var i=0; i<data[0].length; i++){
photoArr.push({"type": "photo", "media": data[0][i], "caption": "Foto "+(i+1)})
}
if(photoArr.length > 0){
sendPhoto(JSON.stringify(photoArr));
}
}
function sendPhoto(photoArray) {
id = "Insert Chat ID here";
var API_TOKEN = "Insert API TOKEN HERE";
var payload = {
'method': 'sendMediaGroup',
'chat_id': String(id),
'media': photoArray,
}
var data = {
"method": "post",
"payload": payload,
'muteHttpExceptions':true,
}
var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + API_TOKEN + '/', data);
}
Sample Data:
Output in Telegram:
File Caption:
References:
Telegram sendMediaGroup
Class Range

Trying to send multiple SMS via twilio in Google Appscript but keep getting errors

Trying to send multiple SMS via twilio in Google Appscript but keep getting errors
Tried this, but the steps are not so clear : https://www.twilio.com/blog/2016/02/send-sms-from-a-google-spreadsheet.html
The author said to define "to" and "body" under Myfunction but the example doesn't show that.
Perhaps i understand it wrongly.
function sendSms(to, body) {
var ACCOUNT_SID = "#########################";
var ACCOUNT_TOKEN = "#########################";
var messages_url = "https://api.twilio.com/2010-04-01/Accounts/" + ACCOUNT_SID + "/Messages.json";
var payload = {
"To": "01#######",
"Body" : "#### Test",
"From" : "+1201########"
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode(ACCOUNT_SID + ":" + ACCOUNT_TOKEN)
};
UrlFetchApp.fetch(messages_url, options);
}
function sendAll() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 31)
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
try {
response_data = sendSms(row[29], row[30]);
status = "Msg Sent";
} catch(err) {
Logger.log(err);
status = "Error";
}
sheet.getRange(startRow + Number(i), 31).setValue(status);
}
}
function specialFunction() {
//var to = "";
//var body = "Tender"
//sendSms(to,body);
sendAll();
}
Error:
30008 - Unknown error
The "Error" or "Msg_Sent" always exceeds my current number of rows(11 rows) but goes upto 18 rows where there isnt a corresponding data to sms.
In your payload in sendSms you're overwriting to, you don't want to do this:
var payload = {
"To": "+60168522468",
"Body" : "RM0.00 Test",
"From" : "+12014313278"
};
Replace "To": "+60168522468", with "To": to, otherwise the SMS is always send to the same recipient.
Also make sure that the rest of the rows are really empty as getLastRow() returns the position of the last row that has content, see the doc.
If possible try to share a sample of the spreadsheet so that we can investigate further.

JSON to Google sheet --> Strange Columns + Everything in one cell

So far i managed to get a connection to a secure JSON. What i dont get to work is the data nice in columns. Plus in the metadata there a nice "labels" but now i get weird column names. Date: Streetname for example.
I have tried a couple of questions on this site. but i dont get it to work.
This is my JSON data (sorry it is in dutch)(so as you can see Project: Zipcode....?):
{
"skip": 0,
"take": 100,
"rows": [
{
"Volgnummer": 1,
"Omschrijving": "Projectnaam",
"Omschrijving_2": "Productnaam",
"Trailercodering": "productnaam-01",
"Omschrijving_3": "Warehouse",
"Datum_laden": "3 juni 2019",
"Tijdstip_laden": "1600 - 1800",
"Datum_aankomst_lossen": "4 juni 2019",
"Tijdstip_lossen": "0800 - 1000",
"Naam": "Transporteur",
"Datum": "Straat"
"Herkomst": huisnummer,
"Navigatie_transport": null,
"Project": "6644 KX",
"Woonplaats": "Ewijk",
"Land": "Nederland"
},
And this is my Google-Script code so far:
function pullJSON1() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getActiveSheet();
var url= "https://the-url.com");
var headers = {
"Authorization": "AfasToken "+
Utilities.base64Encode(<token><version>1</version><data> hier de
token</data></token>)
};
var options = {
"method" : "get",
"headers" : headers
};
var response = UrlFetchApp.fetch(url,options); // get feed
var dataAll = JSON.parse(response.getContentText());
var rows = [Object.keys(dataAll)]; // Retrieve headers.
var temp = [];
for (var i = 0; i < rows[0].length; i++) {
temp.push(dataAll[rows[0][i]]); // Retrieve values.
}
rows.push(temp);
sheet.getRange(1,1,rows.length,rows[0].length).setValues(rows);
// Put values to Spreadsheet.
}
sheet output
(source: imggmi.com)
Can someone help?
I would this rearranged in columns. Also my output in the sheet gives me 1 entry but there a 356 enterys in total.
Great thanks,
Remco
Do you need the "skip", "take" variables? These don't fit with the tabular data, plus they seem to be part of a pagination system (in which case you should probably hide it from the results). Below I provide code to put the actual rows into your sheet:
function pullJSON1() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getActiveSheet();
var url = "https://the-url.com";
var headers = {
"Authorization": "AfasToken " + Utilities.base64Encode("<token><version>1</version><data> hier de token</data></token>");
};
var options = {
"method" : "get",
"headers" : headers
};
var response = UrlFetchApp.fetch(url, options); // get feed
var dataAll = JSON.parse(response.getContentText());
var dataRows = dataAll['rows'];
var rowHeaders = Object.keys(dataRows[0]);
var rows = [rowHeaders]; // Retrieve headers.
for (var i = 0; i < dataRows.length; i++) {
var rowData = [];
for (var j = 0; j < rowHeaders.length; j++) {
rowData.push(dataRows[i][rowHeaders[j]]); // Retrieve values.
}
rows.push(rowData);
}
sheet.getRange(1,1,rows.length,rows[0].length).setValues(rows);
// Put values to Spreadsheet.
}

Fetch json API data from GDAX

I'm trying to get the BTC-EUR ticker from GDAX site to Google Spreadsheet using a script. I got this code but it doesn't work, always returning me error: The coordinates or dimensions of the range are invalid.
var baseUrl = 'https://api.gdax.com';
var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GDAX");
function ticker() {
var request = "/products/btc-eur/ticker";
var requestUrl = baseUrl + request;
var response = UrlFetchApp.fetch(requestUrl);
var json = JSON.parse(response.getContentText());
var rows = [],
jsondata;
for (i = 0; i < json.length; i++) {
jsondata = json[i];
rows.push([jsondata.price]);
}
dataRange = data.getRange(14, 1, rows.length, 1);
dataRange.setValues(rows);
}
I'm using the same code to push my balance to the spreadsheet, and it is working. I cannot understand why this one return me the error. If I log the json var I get the correct values from the site.
Anyone can help? Thank you
How about a following modification?
Modification points :
The JSON data from https://api.gdax.com/products/btc-eur/ticker is as follows. In this data, the value of price is only one. So when the JSON data is always like this, you can directly retrieve the value using json.price.
{
"trade_id": 4314549,
"price": "3691.06000000",
"size": "0.00004053",
"bid": "3691",
"ask": "3691.05",
"volume": "945.78845044",
"time": "2017-01-01T00:00:00.000000Z"
}
When this is reflected to your script, the modified script is as follows.
Modified script :
function ticker() {
var baseUrl = 'https://api.gdax.com';
var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GDAX");
var request = "/products/btc-eur/ticker";
var requestUrl = baseUrl + request;
var response = UrlFetchApp.fetch(requestUrl);
var json = JSON.parse(response.getContentText());
var rows = [[json.price]];
var dataRange = data.getRange(14, 1, 1, 1);
dataRange.setValue(rows);
}
If I misunderstand your question, I'm sorry.

Fetch API data from Bittrex

I'm trying to fetch the API data with Google Apps Script about my balance on Bittrex but it returns me nothing, no errors and only blank cells. This is the code I've written based on the documentation here: https://bittrex.com/Home/Api
function getBalance() {
var ss = SpreadsheetApp.openById("***");
var data = ss.getSheetByName("Data");
var key = ss.getSheetByName("Api").getRange('A2').getValue();
var secret = ss.getSheetByName("Api").getRange('B2').getValue();
var baseUrl = 'https://bittrex.com/api/v1.1/';
var nonce = Math.floor(new Date().getTime()/1000);
var command = "/account/getbalances";
var uri = baseUrl.concat(command + "?apikey=" + key + "&nonce=" + nonce);
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512,
uri,
secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('')
var headers = {
"apisign": signature
}
var params = {
"method": "get",
"headers": headers,
}
var response = UrlFetchApp.fetch(uri, params);
var json = JSON.parse(response.getContentText());
var blnc = [];
blnc.push(['Balance']);
for(var key in json.result)
{
blnc[0].push(json.result[key]);
}
askRange = data.getRange(2, 2, blnc.length, 1);
askRange.setValues(blnc);
}
The askrange last number is "1" because the script only pass the "Balance" value to the spreadsheet, but the values should be something around 210. Any help? Thank you
I solved it, the problem was in the "command" variable, there was a slash not needed that generated an url with a double slash