Undefined Error when parsing JSON in google apps script - javascript

I'm trying to parse JSON I recieved from an API call, but I keep running into the error "TypeError: Cannot read property "id" from undefined. (line 42, file "")" I'm relatively new to Apps Script. Any ideas on what's going on? I can get the payload back in JSON, but can't seem to parse it.
function getInfo() {
var url = "https://subdomain.chargify.com/subscriptions.json";
var username = "xxx"
var password = "x"
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(username + ':' + password)
};
var options = {
"method": "GET",
"contentType": "application/json",
"headers": headers
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
Logger.log(data);
var id = data.subscription; // kicks back an error
// var id = data; works and returns the whole JSON payload
var ss = SpreadsheetApp.getActiveSheet()
var targetCell = ss.setActiveSelection("A1");
targetCell.setValue(id);
}

According to the documentation here
https://docs.chargify.com/api-subscriptions#api-usage-json-subscriptions-list
it returns an array of subscriptions when you call the /subscriptions.json endpoint. So probably your data object should be handled like:
for (var i=0;i<data.length;i++) {
var item = data[i]; //subscription object, where item.subscription probably works
Logger.log(JSON.stringify(item));
}

function getInfo() {
var url = "https://subdomain.chargify.com/subscriptions.json";
var username = "xxx"
var password = "x"
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(username + ':' + password)
};
var options = {
"method": "GET",
"contentType": "application/json",
"headers": headers
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
for (var i = 0; i < data.length; i++) {
var item = data[i]; //subscription object, where item.subscription probably works
Logger.log(JSON.stringify(item));
var subscriptionid = item.subscription.id;
}
var ss = SpreadsheetApp.getActiveSheet()
var targetCell = ss.setActiveSelection("A2");
targetCell.setValue(subscriptionid);
}

Related

"Logging output too large. Truncating output..."

I'm trying to pull data from Airtable using Apps Scripts but all of it doesn't transfer over due to size. What do I need to add/change in order for it work?
function importCA() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ca_sheet = ss.getSheetByName("CA")
var ca = getCA();
ca_sheet.getRange(1,1, ca.length, ca[00].length).setValues(ca)
}
function getCA() {
var ca = requestAirtable();
//console.log("ca: ", ca)
var ca_info = []
ca_info.push(["Name", "Emails", "Districts", "Job Title", "Course", "Completed", "Start Dates"])
for(i=0; i<ca.length; i++) {
var fields = ca[i].fields;
ca_info.push([
fields.Name,
fields.Emails,
fields.Districts,
fields.Title,
fields.Course,
fields.Completed,
fields.StartDates,
])
}
console.log("CA ", ca_info)
return ca_info;
}
function requestAirtable() {
var url = "[removed]"
var headers ={
"Authorization": "[removed]",
"Content-type" : "application/json"
}
var options = {
headers: headers,
method: "GET"
}
var response = UrlFetchApp.fetch(url, options).getContentText();
var result = JSON.parse(response);console.log("result: ", result)
return result.records
}
I tried to altering the line:
for(i=0; i<ca.length; i++) {
but didn't work.
If you must log it to console, you could always log it while you are pushing it to the array instead of trying to log the entire array later.
console.log(ca_info.push([
fields.Name,
fields.Emails,
fields.Districts,
fields.Title,
fields.Course,
fields.Completed,
fields.StartDates
])

TypeError: Cannot find function forEach in object in Google App Script

I keep running to Cannot find function for each in object error while trying to loop entries. Is there something I am not seeing?. Here the code. This code is supposed to fetch time data from a system via API do calculations and send email
function getTime() {
var range = [5323, 9626, 4998];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token'
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + range[i] + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
time_entries.forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
submitted_time_entries.forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
//send mail
}
});
}
}
response.data is probably not the array you expect. The server may be returning an error or a successful response that isn't parseable as an array. To find out, print response.data to the console and confirm it's the array you expect.
Seems my API returned an object. I figured out the way around it by using Object.keys method and it worked. Here is the working code.
function getTime() {
var range = [53, 926, 8098];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token';
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + '449625' + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
Object.keys(time_entries).forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
Object.keys(submitted_time_entries).forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
Logger.log(time_entry)
//send mail
}
});
}
}

How to perform call signing in Java scripts with scripting apps?

I Have the following problem, any help is welcome, I am trying to get result of a function and make a call, but the process is happening as it should, when I step the result in a variable The result is this:
Result URL var parameter
{time_ref = 1554817906, Date_start = 2019-03-10, account_id = xxxxxxxxxx, async_percent_completion = 0, Async_status = Job Not Started, date_stop = 2019-04-08, id = 2299845083590625}
Passing direct the value in the URL The result is this:
Manual
{time_ref = 1554817906, Date_start = 2019-03-10, account_id = xxxxxxxxxx, time_completed = 1554817907, async_percent_completion = 100, Async_status = Job Completed, date_stop = 2019-04-08, id = 2299845083590625}
What am I doing wrong that I can't get the second call I need to finalize my lawsuit?
Documentation :
https://developers.facebook.com/docs/marketing-api/insights/best-practices/?hc_location=ufi#asynchronous
function solicitacaoAssicrona(){
var service = getService()
var metricas = [
'impressions',
'reach',
'unique_clicks',
'account_currency',
'account_id',
'account_name',
'ad_id',
'ad_name',
'adset_id',
'adset_name',
'buying_type',
'campaign_id',
'campaign_name',
]
var parameters = metricas.join(',');
var url = 'https://graph.facebook.com/v3.2/act_xxxxxxxxxx/insights?fields=' + parameters + '&level=ad';
//Logger.log(url);
var report_run_id = UrlFetchApp.fetch(url, {
method: 'POST',
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(report_run_id.getContentText());
return result;
}
result= [19-04-09 12:28:34:334 BRT] {report_run_id=1283453988472584}
function reportId(){
var service = getService();
var report_run_id = new solicitacaoAssicrona();
//Logger.log(report_run_id);
var report = report_run_id['report_run_id'];
//var report_run_idParameters = report.toString();
var reportUrl = 'https://graph.facebook.com/v3.2/' + report;
//Logger.log(reportUrl);
var response = UrlFetchApp.fetch(reportUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
return result;
}
[19-04-09 12:30:38:457 BRT] {time_ref=1554823837, date_start=2019-03-10, account_id=xxxxxxxxx, async_percent_completion=0, async_status=Job Not Started, date_stop=2019-04-08, id=806453509753109}
function reportId(){
var service = getService();
var report_run_id = new solicitacaoAssicrona();
//Logger.log(report_run_id);
var report = report_run_id['report_run_id'];
//var report_run_idParameters = report.toString();
var reportUrl = 'https://graph.facebook.com/v3.2/806453509753109';
//Logger.log(reportUrl);
var response = UrlFetchApp.fetch(reportUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(result)
return result;
}
[19-04-09 12:31:26:785 BRT] {time_ref=1554823837, date_start=2019-03-10, account_id=xxxxxxxx, time_completed=1554823839, async_percent_completion=100, async_status=Job Completed, date_stop=2019-04-08, id=xxxxxxx}
Solved with caching, I stored the report ID in cache there worked well! Follow Documentation! https://developers.google.com/apps-script/reference/cache/cache

How to login through api from Google Script?

I'm now working on the api of Gatecoin and want to get my open order on Google Sheet. I'm trying this:
function GetOrder() {
var method = "GET"
var URL = "https://api.gatecoin.com/Trade/Orders"
var contentType = "application/json"
var d = new Date()
var now = d.getTime()
var msg = method + URL + contentType + now
var publicKey = :Public_key
var privateKey = :Private_key
var hash = Utilities.computeHmacSha256Signature(msg, privateKey, Utilities.Charset.US_ASCII);
var hashInBase64 = Utilities.base64Encode(hash);
var options ={
'contentType': 'application/json',
'method': method,
'API_PUBLIC_KEY': publicKey,
'API_REQUEST_SIGNATURE': hashInBase64,
'API_REQUEST_DATE': now
};
var rdata = UrlFetchApp.fetch("https://api.gatecoin.com/Trade/Orders", options)
}
But the response mentions I was not logged in. What am I doing wrong?
I believe your options should have headers defined in an object as such:
var options ={
“contentType”: “application/json”,
“method”: method,
“headers”: {
“API_PUBLIC_KEY”: publicKey,
“API_REQUEST_SIGNATURE”: hashInBase64,
“API_REQUEST_DATE”: now
}
};

Node.JS and Object.Keys with json

The Code:
(URL is a working rest api that passes json data)
var request = require('request');
var username = "user";
var password = "pass";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var url = "URL";
request(
{
method: "GET",
url : url
},
function (error, response, data) {
console.log(data);
var initial_index = Object.keys(data.sites)[0];
var product_index = Object.keys(data.sites[initial_index].products)[0];
var order_id = data.purchase_id;
var title = data.sites[initial_index].products[product_index].title;
var content = data.sites[initial_index].products[product_index].description;
var image = data.sites[initial_index].products[product_index].image;
var total_price = data.sites[initial_index].prices.final_price;
var quantity = data.sites[initial_index].products[product_index].input_fields.quantity;
var sold_by = data.sites[initial_index].info.name;
var order_status = data.sites[initial_index].status;
var datatwo = {
"status": "published",
"order_id": order_id,
"title": title,
"content": content,
"image": image,
"final_price": total_price,
"quantity": quantity,
"sold_by": sold_by,
"order_status": order_status
};
}
);
I receive this error when running the code. How can it be resolved?
var initial_index = Object.keys(data.sites)[0];
^
TypeError: Cannot convert undefined or null to object
You're not parsing the JSON (which is text) you get back. Add this at the top of your request callback:
data = JSON.parse(data);
E.g.:
request(
{
method: "GET",
url : url
},
function (error, response, data) {
data = JSON.parse(data);
var initial_index = Object.keys(data.sites)[0];
// ...
One you've parsed it, you'll have an object tree you can traverse.

Categories

Resources