This is probably a very novice question, but I am a very novice programmer, so here goes...
I am using GAS and Google Books to get the url for a book cover using this code:
function myFunction() {
var url = "https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&country=US"
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(response);
}
From my limited knowledge, I tried using this to get the proper URL:
Logger.log(data.items.imageLinks.smallThumbnail);
but it just returns an error. Is there something missing or a different way to get the variable I need?
The issue is that data.items is an array of 10 elements, therefore you have to index that.
If you want to access the first element:
function myFunction() {
var url = "https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&country=US"
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(data.items.length)
Logger.log(data.items[0].volumeInfo.imageLinks.smallThumbnail);
}
If you want to access all elements and store it in an array:
function myFunction() {
var url = "https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&country=US"
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var items = data.items;
var smallThumbnails = items.map(x=>x.volumeInfo.imageLinks.smallThumbnail);
Logger.log(smallThumbnails);
}
Output:
[http://books.google.com/books/content?id=gK98gXR8onwC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=LRlCAAAAYAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=Fgn65IL3q4wC&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=3vFDvgAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=gK98gXR8onwC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=F1wgqlNi8AMC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=64tuPwAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=wAUiAAAAMAAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=7hLQ_F0obXAC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=tVxnDwAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api]
Related
I have a google app script that allows me to retrieve data via a public API and a fetch. So far so good. I initialized a table in order to push the data into it, then I call a function that will send the data to a column of my google sheets table. My first function fills the array with a "while" loop, when the length of the array reaches 12, my "pushDatasToSheet" function launches but I have an error, the console tells me that my data range is at 1 and therefore does not correspond not in range of my selected cells. What is funny is that my table does indeed indicate a length of 12 when executing my function sending data to the table and when I modify the range of my cells by putting only one , the console shows me 12 for my data range. I can't find where my mistake is coming from. thank you in advance for your help.
Here an image of the console error:
error code in app script console
And my code:
const signsList = ["aries", "taurus", "gemini", "cancer", "leo", "virgo", "libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces"];
var SHEET_NAME = "horoscope";
const options = {
'method': 'post',
};
var rowDescription = [];
// Get horoscopes from API
function doPost(e) {
signsList.forEach(sign => {
while (rowDescription.length < 12) {
var url = 'https://aztro.sameerkumar.website/?sign=' + sign + '&day=today';
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
rowDescription.push(data.description);
}
pushDatasToSheet();
})
}
function pushDatasToSheet() {
Logger.log(rowDescription.length);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
var descriptionColumn = sheet.getRange('B2:B13');
descriptionColumn.setValues([rowDescription]);
};
Problem solved 😅
In case another person with the same problem happen, the array have to be a 2D array. And i have changed my while loop for a if statement.
Here the correction snippet:
const signsList = ["aries", "taurus", "gemini", "cancer", "leo", "virgo", "libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces"];
var SHEET_NAME = "horoscope";
const options = {
'method': 'post',
};
var rowDescription = [];
// Get horoscopes from API
function doPost(e) {
if (rowDescription.length < 12) {
signsList.forEach(sign => {
var url = 'https://aztro.sameerkumar.website/?sign=' + sign + '&day=today';
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
rowDescription.push([data.description]);
})
}
pushDatasToSheet();
}
function pushDatasToSheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
sheet.getRange('B2:B13').setValues(rowDescription);
};
So I have multiple script. One script retrieves data from a Googlesheet and parses it as JSON. The other one uses this to output it to HTML.
My first:
function getStatistics() {
var sheet = SpreadsheetApp.openById("ID");
var rowsData = sheet.getRange("A:A").getValues();
var result = JSON.stringify(rowsData);
var funcNumber = 1;
return result;
}
This retrieves the data from a spreadsheet in column A.
The second script, here I want to use both 'Result' and 'Funcnumber' in my function.
function onSuccess(data, funcNumber) {
var dataJson = JSON.parse(data);
var newColumn = document.createElement("div");
newColumn.className = "column";
for(var i = 0; i < dataJson.length; i++) {
if (dataJson[i] != "") {
var div = document.getElementById('cont-' + funcNumber);
var newDiv = document.createElement("div");
newDiv.innerHTML = dataJson[i];
newColumn.appendChild(newDiv);
}
}
div.appendChild(newColumn);
}
Using the Json result to PARSE the HTML works. But retrieving 'funcNumber' from the function not. Then finally I call the first function with this line:
google.script.run.withSuccessHandler(onSuccess).getStatistics();
Does anybody know how to use both result and funcNumber in my second function?
function getStatistics() {
var ss = SpreadsheetApp.openById("ID");
const sheet = ss.getSheetByName('Sheet1');
let result = {data:JSON.stringify(sheet.getRange(1,1,sheet.getLastRow(),1).getValues()),funcNumber:1}
return result;
}
function onSuccess(obj) {
var dataJson = JSON.parse(obj.data).flat();
var newColumn = document.createElement("div");
newColumn.className = "column";
for (var i = 0; i < dataJson.length; i++) {
if (dataJson[i] != "") {
var div = document.getElementById('cont-' + obj.funcNumber);
var newDiv = document.createElement("div");
newDiv.innerHTML = dataJson[i];
newColumn.appendChild(newDiv);
}
}
div.appendChild(newColumn);
}
A single column or row is still a 2d array
Following is the way to make the call in Google script to return the value for the 2nd parameter.
google.script.run
.withSuccessHandler(onSuccess)
.withUserObject(funcNumber)
.getStatistics()
WithUserObject() needs to be called after the withSuccessHandler.
See the documentation below on Google script
withUserObject(object)
Sets an object to pass as a second parameter to the success and failure handlers. This "user object" — not to be confused with the User class — lets the callback functions respond to the context in which the client contacted the server. Because user objects are not sent to the server, they are not subject to the restrictions on parameters and return values for server calls. User objects cannot, however, be objects constructed with the new operator.
I am having trouble with looping JSON data. I always get the error data.forEach is not a function even do i use JSON.parse. Anyone know how to fix this problem ?
function getApiGebruiker() {
CallWebAPI();
//nieuw deel
var url = "http://localhost:8081/persoons";
//do get request
var client = new HttpClient();
client.get("http://myIPadress/persoons", function (response) {
// do something with response
var data = JSON.parse(response);
console.log(data);
//data = JSON.parse(data);
let string = document.getElementById("pwd").value;
let loginn = document.getElementById("login").value;
data.forEach((persoons) => {
console.log(persoons.gebruikersnaam);
});
});
Your data seems to be an object ({}) and not an array ([]).
Try:
var data = JSON.parse(response);
var people = data._embedded.persoons
people.forEach((persoon) => {
console.log(persoon.gebruikersnaam);
});
Now, I have tried to get some data from crawling website.
The target website provides current status of bicycle stations using google map.
GDownloadUrl("/mapAction.do?process=statusMapView", function(data, responseCode) {
var jsonData = eval("(" + data + ")");
//alert(jsonData.centerLat);
var length = jsonData.markers.length;
//if (length > 100) length = 100;
for (var i = 0; i < length; i++) {
var point = new GLatLng(parseFloat(jsonData.markers[i].lat), parseFloat(jsonData.markers[i].lng));
var name = jsonData.markers[i].name;
var cntRackTotal = jsonData.markers[i].cntRackTotal;
var cntRentable = jsonData.markers[i].cntRentable;
var cntLockOff = jsonData.markers[i].cntLockOff;
var cntPrtRack = jsonData.markers[i].cntPrtRack;
var percent = jsonData.markers[i].percent;
var imgFile = jsonData.markers[i].imgFile;
var number = jsonData.markers[i].kiosk_no;
//map.addOverlay(createMarker(number, point, name, cntRackTotal, cntRentable, cntLockOff, cntPrtRack, percent, imgFile ));
}
});
This JS source code is used on target website. In GDownloadUrl callback function, the parameter "data" contains current status of bicycle stations. And I want to get data.
Now, I tried using python selenium and execute_script().
jsSourcecode = ("var strData;"+
"strData = GDownloadUrl('/mapAction.do?process=statusMapView',"+
" function(data, responseCode) {return data;}); return strData;")
data = driver.execute_script(jsSourcecode)
this source code is that I used to get data. I expected data on callback would be stored on var strData and the return value of execute_script() would be the data. but the return value is just "True".
I have little knowledge about js.. How can I get the data? Please help
The function you are calling is asynchronous and requires a callback function as argument.
Use execute_async_script and provide the callback present in the last argument:
data, status = driver.execute_async_script("""
var callback = arguments[0];
window.GDownloadUrl('/mapAction.do?process=statusMapView', function(data, status){
callback([data, status]);
});
""")
I am trying to pull data, using JQuery, out of an unlabelled array of unlabelled objects (each containing 4 types of data) from a JSON api feed. I want to pull data from the first or second object only. The source of my data is Vircurex crypto-currency exchange.
https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC
By 'unlabelled' I mean of this format (objects without names):
[{"date":1392775971,"tid":1491604,"amount":"0.00710742","price":"40.0534"},{ .... }]
My Javascript look like this:
var turl = 'https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC';
$.getJSON(turl, function (data) {
$.each(data, function(key,obj) {
var ticker1tid = obj[1].tid;
var ticker1amount = obj[1].amount;
var ticker1date = obj[1].date;
var ticker1price = obj[1].price;
});
});
Somehow I am not calling in any data using this. Here is link to my sand-box in JSFiddle: http://jsfiddle.net/s85ER/2/
If you just need the second element in the array, remove the traversing and access it directly from the data:
var turl = 'https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC';
$.getJSON(turl, function (data) {
var ticker1tid = data[1].tid;
var ticker1amount = data[1].amount;
var ticker1date = data[1].date;
var ticker1price = data[1].price;
// Or isn't it better to just have this object?
var ticker = data[1];
ticker.tid // 1491736
ticker.amount // 0.01536367
// etc
});