How to dictionary in this case with GAS? - javascript

I'm a newbie and non-native...
function fetch_json() {
var result = UrlFetchApp.fetch("https://api.ookami.me/v1/news/public?sport_id=1");
var obj = JSON.parse(result.getContentText());
var ss = SpreadsheetApp.openById("1ecv2r3qBEuHWyP4XH7FkGktQ7YHqegd7CztRoARzKac");
var sheet = ss.getSheetByName("soccer");
for (var n=0; n < 10; n++) {
var news = json["news"][n];
var a = news["id"];
var b = news["title"];
var c = news["summary"];
var d = news["media_name"];
var e = news["url"];
var f = news["image"];
var array = [a, b, c, d, e, f];
var columnA = sheet.getRange(2, 1);
var valuesA = columnA.getValues();
var maxid = valuesA[0][0];
if (a > maxid) {
sheet.appendRow(array);
}else{
break
}
sheet.setColumnWidth(6, 120);
var last_row = sheet.getLastRow();
if (f != null) {
var cell = sheet.getRange(last_row, 6);
var image_cell = "=IMAGE(\"" + f + "\", 1)";
cell.setValue(image_cell);
sheet.setRowHeight(last_row, 72);
}else{
sheet.setRowHeight(last_row, 72);
}
}
sheet.autoResizeColumn(1);
sheet.sort(1, false);
}
This is a complete code. I want to run same function simply to other sheets by using other url.
var result= UrlFetchApp.fetch("https://api.ookami.me/v1/news/public?sport_id=1");
"sport_id=1" → "sport_id=2", "sport_id=3"..."sport_id=37".
And
var sheet = ss.getSheetByName("soccer");
"soccer" → "baseball", "tennis"..."sportsbusiness"(37 sheets).
baseball:2(id), tennis:3..., sportsbusiness:37
And I imagine like this
function a () {
//I don't know the code I want to write
function fetch_json ()
}
Is it possible?
I don't understand about "dictionary" method, so if there're other ways, plz teach me.

If I understand correctly, you want to get data from different urls and write the data to different sheets in the same spreadsheet based on the sport. I would first define an object for all of the sports:
var sportIds = {
0: 'soccer',
1: 'baseball',
2: 'tennis',
...
36: 'sportsbusiness'
};
In the above object, the keys are the IDs in your url and the values are the sheet names. Then, you can loop through the object and grab/write the data using something like:
var urlBase = "https://api.ookami.me/v1/news/public?sport_id=";
for (var id in sportIds){
var url = urlBase+id; // Generate the url using the id/key from the object
var result = UrlFetchApp.fetch(url);
var sheet = ss.getSheetByName(sportIds[id]);
// write to the sheet as desired
}
Here, you generate the url using the key in the object and get the sheet you want to write to using the corresponding value. It seems like that should do it. Please comment if this isn't what you're looking for.

Related

How to filter an array using the filtered index of another array?

My current code grabs the values of the same range of data for Values, Notes, and Background Colors into 3 separate arrays. Then it filters the Values array by the first item in the nested array, returning only the items that matches the defined statArray array item. Now I want the other two array filters (Notes, Background) to be filtered by the indexes of the returned items from the filtered Value array. That way when I set the Backgrounds and Notes arrays they overlap correctly onto the values.
function moveAllNew() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = SpreadsheetApp.getActiveSheet();
var activeSheetName = activeSheet.getName();
var lastRow = activeSheet.getLastRow();
var lastColumn = activeSheet.getLastColumn();
var statArray = ["Captures Sent 📩","QA In Progress 👌","Bagging in Progress 01 🎒","Bagging in Progress 02 🎒","Bag Sent 📩","Bag Rejected ❌","Bag Accepted ✅","Captured 📷",""];
var rowHeaderCount = 3;
var rowStart = 4;
var columnFormulaB = 2;
var columnFormulaS = 19;
var columnFormulaAC = 29;
// gets the range of the current sheet
var activeRange = activeSheet.getRange(rowStart,1,lastColumn-rowHeaderCount,lastColumn);
var activeRangeFormulaB = activeSheet.getRange(rowStart,columnFormulaB,lastRow-rowHeaderCount);
var activeRangeFormulaS = activeSheet.getRange(rowStart,columnFormulaS,lastRow-rowHeaderCount);
var activeRangeFormulaAC = activeSheet.getRange(rowStart,columnFormulaAC,lastRow-rowHeaderCount);
// creates array of the active sheet (values, notes, backgrounds, and formula columns (B, S, AC))
var activeRangeValues = activeRange.getValues();
var activeRangeNotes = activeRange.getNotes();
var activeRangeBackgrounds = activeRange.getBackgrounds();
var activeRangeFormulaB = activeRangeFormulaB.getFormulasR1C1();
var activeRangeFormulaS = activeRangeFormulaS.getFormulasR1C1();
var activeRangeFormulaAC = activeRangeFormulaAC.getFormulasR1C1();
// filtered QA arrays
var qaSheet = ss.getSheetByName("QA 👌");
var qaRangeValues = activeRangeValues.filter(function(item){return item[0] === statArray[0] || item[0] === statArray[1];});
var qaRangeNotes = activeRangeNotes.filter(function(item){return item[0] === statArray[0] || item[0] === statArray[1];});
var qaRangeBackgrounds = activeRangeBackgrounds.filter(function(item){return item[0] === statArray[0] || item[0] === statArray[1];});
Logger.log(qaRangeValues);
Logger.log(qaRangeNotes);
Logger.log(qaRangeBackgrounds);
Currently the qaRangeValues and qaRangeNotes arrays would come back empty because the statArray item is never a color nor a note value.
Probably you meant to use lastRow instead of lastColumn when determining activeRange.
Anyway, you need to perform some operation that allows you to access the current indices, and while you have the indices, also operate on your other equal-sized arrays.
One example:
var qaData = {values: [], notes: [], bgs: [] };
activeRangeValues.forEach(function (row, idx) {
if (row[i] === statArray[0] || row[i] === statArray[1]) {
qaData.values.push(row);
qaData.notes.push(activeRangeNotes[idx]);
...
});
// Use the qaData object

Iterating over an object in a Google Apps script and printing to Google Sheets

I'm having trouble printing more than one row to my google sheet with this loop.
The first row appends fine, but I want the function to append all objects from the data var.
The data object is properly pulling from Firebase when I verify with a Logger.
var firebaseUrl = "https://test.firebaseio.com/alerts";
var secret = "sssssssssssssssssssss";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
var data = base.getData();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("feed");
var selection = sheet.getActiveRange();
var range = sheet.getActiveRange();
var values = range.getValues();
var columns = selection.getNumColumns();
var rows = selection.getNumRows();
var num = 2;
function writeToSheets() {
for(var i in data) {
var values = [
[ data[i].id, data[i].two, data[i].three, data[i].four ]
];
var keys = Object.keys(values[0]);
var sheetRow = [];
var entryKeys;
for (j in keys) {
sheetRow = [];
entryKeys = Object.keys(values[keys[j]])
for (k in entryKeys) {
sheetRow.push(values[keys[j]][entryKeys[k]]);
}
sheet.appendRow(sheetRow);
}
}
}
I've just tried this code (assuming that I guessed the data structure correctly):
function myFunction() {
var data = [
{'id': 1, 'two': 'test2', 'three': 'test3', 'four': 'test4'},
{'id': 2, 'two': 'test2-2', 'three': 'test3-2', 'four': 'test4-2'}
]
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("feed");
var selection = sheet.getActiveRange();
var range = sheet.getActiveRange();
var values = range.getValues();
var columns = selection.getNumColumns();
var rows = selection.getNumRows();
var num = 2;
function writeToSheets() {
for(var i in data) {
var values = [
[ data[i].id, data[i].two, data[i].three, data[i].four ]
];
var keys = Object.keys(values[0]);
var sheetRow = [];
var entryKeys;
for (j in keys) {
sheetRow = [];
entryKeys = Object.keys(values[keys[j]])
for (k in entryKeys) {
sheetRow.push(values[keys[j]][entryKeys[k]]);
}
sheet.appendRow(sheetRow);
}
}
}
writeToSheets();
}
When I run it, it fails after printing the first line with an error TypeError: Expected argument of type object, but instead had type undefined. (line 26, file "Code").
And it is easy to see what exactly happens if you run it in debug mode:
You have values array with one element (line 18)
The var keys = Object.keys(values[0]); becomes [0,1,2,3] (we have 4 values inside the first element of values array)
Then, having j from 0 to 3 we get entryKeys = Object.keys(values[keys[j])
When j = 0, values[keys[j]] = values[0] - we get the first element from values
When j = 1, values[keys[j]] = values[1] - here we fail, because there is only 1 element in values
I am not really sure what you are trying to do here with all these keys, but if you just want to print the data, it can be done simpler:
function writeToSheets() {
for(var i in data) {
var item = data[i];
sheetRow = [];
for (key in item) {
sheetRow.push(item[key]);
}
sheet.appendRow(sheetRow);
}
}

How to parse JSON value from MQTT client to plotly javascript

Hi I have this json type data how can I access P , T , F , W and M data using javascript?
{"PHILMG":[{"P":"10"}, {"T":"5"}, {"F":"0"}, {"W":"0"}, {"M":"0"}]}
so far I tried.
function onMessageArrived(message) {
ss = message.payloadString;
console.log(ss);
// var p = ss.PHILMG.P;
// var time = ss.PHILMG.T;
// var f = ss.PHILMG.F;
// var w = ss.PHILMG.W;
// var m = ss.PHILMG.M;
// var timecollect = [];
// var windcollect = [];
// timecollect.push(time);
// windcollect.push(wind);
// console.log(windcollect);
// var data =
// {
// type:'scatter',
// x: time,
// y: w
// };
// Plotly.newPlot(document.getElementById('PhilMg'), data);
}
But Im getting an error
Object {errorCode: 5, errorMessage: "AMQJS0005E Internal error. Error Message: Cannot r…ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js:19:132)"}
Parse your JSON string with JSON.parse, then loop over the array and push the keys and values to the data which is visualized with Plotly.
var message = '{"PHILMG":[{"P":"10"}, {"T":"5"}, {"F":"0"}, {"W":"0"}, {"M":"0"}]}';
var msg = JSON.parse(message);
var x = [];
var y = [];
var i = 0;
var j;
var k;
for (k in msg) {
for (i = 0; i < msg[k].length; i += 1) {
for (j in msg[k][i]) {
x.push(j);
y.push(msg[k][i][j]);
}
}
}
var data = [{
x: x,
y: y,
type: 'bar'
}];
Plotly.newPlot('myDiv', data);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id='myDiv'></div>
You should use the correct index of the array you have in your object to reach the respective inner object at each assignment.
// var p = ss.PHILMG[0].P;
// var time = ss.PHILMG[1].T;
// var f = ss.PHILMG[2].F;
// var w = ss.PHILMG[3].W;
// var m = ss.PHILMG[4].M;
You can see the log in developer tools,
If you see this,
Object {PHILMG: Array[5]}
You should use the index of the array to get the object, then use key to get the value.
If you see this,
"{"PHILMG":[{"P":"10"}, {"T":"5"}, {"F":"0"}, {"W":"0"}, {"M":"0"}]}"
You should use ss = JSON.parse(ss), and same as above.

Handling of array; returned by methods in iOS UI Automation

I have been able to use all the methods for automating iphone app test except with ones which returns array... e.g elements()
I have tried to do it using declaration of array as
var arr = [];
var arr = UIATarget.localTarget().frontMostApp().mainWindow().tabBar().elements();
UIALogger.logPass("result"+ arr[0]) // just to get first element
But it is not working
Can someone ans how to handle array. What is the correcting required?
What exactly do you want from such array?
Here is an example how to handle array of elements:
function getAllNamesInList (list, index){
var elem_list = list[index].elements();
var elem_count = elem_list .length;
var names = [];
var elem_name;
for (var elem_ind = 0; elem_ind < elem_count ; elem_ind++){
elem_name= elem_list [cell_ind].name();
if (!elem_name){fail ("TEST_INFO: Empty Element name!!!");}
names.push(elem_name);
}
return names;
};
Here is usage example of this function():
Your case:
var app = UIATarget.localTarget().frontMostApp();
var window = app.mainWindow();
var arr = window.tabBar()
var current_names = [];
current_names = getAllNamesInList (arr , 0);
UIALogger.logMessage ("Here are ALL names from array " + current_names );
Other possible lists which can be transferred and used within this function():
var table_views = window.tableViews();
var tab_bar = app.tabBar();
var nav_bar = app.navigationBar();

How to get all possible combinations of multiple sets where order matters recursively

Given multiple sets of values. I want to find every combination (sorry I am using this term loosely but am not sure what the correct word is) of those values while preserving the order.
ie for
var set1 = ["a","1"];
var set2 = ["b","2"];
var set3 = ["c","3"];
the output should be
[a][b][c]
[a][b][3]
[a][2][c]
[a][2][3]
[1][b][c]
[1][b][3]
[1][2][c]
[1][2][3]
This provides the correct results, but I don't think this is a very good solution but just can't wrap my head around doing this recursively. The example is in Javascript but any language or insight is fine.
var set1 = ["a","1"];
var set2 = ["b","2"];
var set3 = ["c","3"];
var input = [set1, set2, set3];
var result = [];
for(var a=0;a<input[0].length;a++){
for(var i=0;i<input[1].length;i++){
for(var j=0;j<input[2].length;j++){
var output = [];
output.push(input[0][a]);
output.push(input[1][i]);
output.push(input[2][j]);
result.push(output);
console.log("["+input[0][a]+"]["+input[1][i]+"]["+input[2][j]+"]");
}
}
}
Sure, you can recursively explore the space like this:
function extend_set (base, sets) {
if(sets.length === 0) {
return console.log('found: '+base);
}
sets = sets.slice();
var choices = sets.shift();
for (var i = 0; i < choices.length; i += 1) {
var b2 = base.slice();
b2.push(choices[i]);
extend_set(b2, sets);
}
}
var set1 = ["a","1"];
var set2 = ["b","2"];
var set3 = ["c","3"];
var sets = [set1, set2, set3];
extend_set([], sets);

Categories