Parsing a stringified JSON coming from a Google Sheet Web App - javascript

I'm trying to parse a stringified JSON output from a web app created from a google sheets script. I thought it couldn't be that complicated, but I've tried everything I could think of or find out online... so now asking for help if that's OK!
on the web app / Google Sheets side, the code is:
function doGet(e) {
var spreadsheet = SpreadsheetApp.openById('spreadsheetID');
var worksheet = spreadsheet.getSheetByName('Rankings C/U');
var output = JSON.stringify({ data: worksheet.getDataRange().getValues() });
return HtmlService.createHtmlOutput(output);
}
I've published the script, the web app works, I'm OK with that bit.
I've put random values on the spreadsheet: [[1,2],[3,4]] if we speak in matrix format.
on the other end, I've tried a bunch of stuff including .fetch, JSON.parse() to get the data in a usable format within the Google Sites embedded code, but the real issue is that I think I can't get to allocate the payload to a variable?
I'm using Google Sites to fetch the data.
with the basic module "<> embed", with the "by URL" option, with the following code:
https://script.google.com/macros/s/scriptID/exec
I get the following output - that looks what it should be:
{"data":[[1,2],[3,4]]}
but when trying to include this in a script module ("embed code") - no chance!
<form name="get-images">
<input name="test" id="test" value="we'll put the contents of cell A1 here">
</form>
<script>
const form = document.forms['get-images']
var usableVariable = JSON.parse("https://script.google.com/macros/s/scriptID/exec"); // here I'm trying to allocate the stringified JSON to a variable
form.elements['test'].value = usableVariable[1,1]; //allocating the first element of the parsed array
</script>
I'm pretty sure I'm missing something obvious - but now I ran out of ideas!
Thanks for any help :)

I believe your goal as follows.
In your situation, the bottom script is embedded to the Google site.
You want to retrieve the values from doGet and want to put the value of cell "B2" to the input tag.
The settings of Web Apps is Execute the app as: Me and Who has access to the app: Anyone, even Anonymous.
Modification points:
In your case, I think that return ContentService.createTextOutput(output); is suitable instead of return HtmlService.createHtmlOutput(output); in Google Apps Script.
In order to retrieve the values from doGet, in this modification, fetch is used.
You want to retrieve the cell "B2" from usableVariable[1,1];, please modify it to usableVariable[1][1];
When above points are reflected to your script, it becomes as follows.
Modified script:
Google Apps Script side:
function doGet(e) {
var spreadsheet = SpreadsheetApp.openById('spreadsheetID');
var worksheet = spreadsheet.getSheetByName('Rankings C/U');
var output = JSON.stringify({ data: worksheet.getDataRange().getValues() });
return ContentService.createTextOutput(output);
}
HTML & Javascript side:
<form name="get-images">
<input name="test" id="test" value="we'll put the contents of cell A1 here">
</form>
<script>
let url = "https://script.google.com/macros/s/###/exec";
fetch(url)
.then((res) => res.json())
.then((res) => {
const usableVariable = res.data;
const form = document.forms['get-images'];
form.elements['test'].value = usableVariable[1][1]; // usableVariable[1][1] is the cell "B2".
});
</script>
Note:
When you modified the Google Apps Script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be careful this.
In my environment, I could confirm that above HTML & Javascript worked in the Google site by embedding.
References:
Class ContentService
Using Fetch
Web Apps

Related

How to use Google Sheets as read-only database for Angular, without making the sheet public

I'm trying to use Google Sheets document as read-only database for my angular application.
I tried some methods to do that, but the problem with all of these methods is that they require the Sheet to be shared publicly (anyone with the link can access the sheet). But what I want is to share it with specific user using Service Account through credentials.
I'm using Angular 14
There is no reference to Angular in Google Sheets for Developers.
If you know any solution or come across an article about this topic, please share it with me.
Thank you.
Here are the steps you'll need to take in order to read from Google Sheets into Angular:
Step 1: Prepare your Google Sheet
1.) Make sure ALL the cells in your sheet are formatted as "Plain text". To do this, click in the upper-left corner of the sheet nexus where the rows and columns intersect to select all cells, then select Format > Number > Plain text from the top menu.
2.) Go to Share, then under "General Access", select "Anyone with the link", then click Done. I believe in your case that this step is optional, since you do not want the sheet to be public.
3.) Go to File > Share > Publish to web in the top menu. Set the scope of what you want to publish, then click Publish. Unfortunately in your case, this step is NOT optional!
Step 2: Fetch the Google Sheet Data
Use the following code example to fetch the raw data from your Google Sheet as plain text:
const docId = '1vLjJqvLGdaS39ccsvoU58kEWXngzV_VXtto07Ki6qVo';
const sheetId = ''; // to get a specific sheet by ID, use '&gid=###'
const url = `https://docs.google.com/spreadsheets/d/${docId}/gviz/tq?tqx=out:json${sheetId}`;
this.http.get(url, {
responseType: 'text',
}).subscribe((response: string): void => {
console.log(response);
});
Step 3: Parse the Raw Text as JSON
Use the following example to parse the raw text to JSON:
const rawJSONText = response.match(/google\.visualization\.Query\.setResponse\(([\s\S\w]+)\)/); // strip the header response
const json = JSON.parse(rawJSONText[1]);
console.log(json);
Hope this helps. Cheers!

JS Array not recognized as an array in Google Apps script

I am writing what should be a simple HTML form for users to make a reservation. However, having difficulty doing something I've done many times before - getting data from a GSheet and presenting it in an HTML form. Code snippets:
**Server side**
//Getting data from spreadsheet; expecting it to be an array of arrays.
function getMembers(){
const url = "https://my gsheet url"
const ss = SpreadsheetApp.openByUrl(url);
const ws = ss.getSheetByName("Members");
const row = ws.getLastRow()
const memberData = ws.getRange(2,1,row-1,7).getValues();
const array = JSON.stringify(memberData); //EDIT...helps get data to client side
return //array; //this data to be passed to browser when called. Type Error?
//Log(memberData) = //Looks like an array to me...
//[1,"Simmie","Smith","Simmie Smith","2020-01-01T05:00:00.000Z","temp","53120-1"],
//[2,"Fred","Williams","Fred Williams","2020-01-01T05:00:00.000Z","temp","53120-2"],
//[3,"Carleton","Johnson","Carleton Johnson","2020-01-01T05:00:00.000Z","temp","53120-3"],
//[4,"Caroll","Williams","Caroll Williams","2020-01-01T05:00:00.000Z","temp","53120-4"],
//[5,"Gabby","Williams","Gabby Williams","2020-01-01T05:00:00.000Z","temp","53120-5"]
//EDIT HtmlService code
function doGet(e){
return HtmlService.createTemplateFromFile('Reservations HTML')
.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Calling the above server function when page loads so that member name can be presented in a select dropdown and other info from the array used elsewhere.
**Browser JS**
function getMemberData(){
google.script.run.withSuccessHandler(populateMembersDD).getMembers();
}
function populateMembersDD(data){
console.log(data) //undefined - same result FFox or Chrome..
memberInfo = data.filter(function(row){return true});
not getting any further than that because data is not passing to browser in a format with which I can apply necessary methods to get data into dropdown. Have tried various methods (slice, filter etc) to convert data into an array but none have worked. I suspect a type error, as though server function is not producing an object in array format. But I cannot figure out why. Have read many similar questions/answers on Stack but none have solved my problem. Help much appreciated as I am 24 hours in on solution experiments. Have many other apps where this basic code pattern works totally fine...

How to get data from Viadeo with X-Ray and NodeJs

So I am trying to scrape some content with node.js x-ray scraping framework. While I can get the content from a single page but for exemple only for one employee I can't get my head around on how to get for all the employees.
Working Exemple but return me the first employee:
const request =require('request');
const Xray=require('x-ray');
var x = Xray();
x('http://www.viadeo.com/fr/company/unicef',
'.pan',[{
name:'.pan-emp-name',
job:'.pan-emp-pos',
since:'.pan-emp-age'
// job:'#profile #overview-summary-current ol'
}]).write('result.json')
Thank you so much
x('http://www.viadeo.com/fr/company/unicef',
'#pan-emp .pan-employees .pan-empployee',[{
company:'#company-info .company-logo-picture',
nom:'.pan-emp-name',
job:'.pan-emp-pos',
depuis:'.pan-emp-age'
// job:'#profile #overview-summary-current ol'
}]).write('result.json')
Working like a charm,
So now my problem is to get the company info

Appending new Google Sheets Data into BigQuery Table

So I'm new to all of this, both BigQuery and AppScript (coding in general..) and I'm learning as I go, so maybe to some my question may seem stupid. Please just hear me out.
I have created a script that loads 10 of the most recent data points into a Google Sheets doc from one of my BigQuery tables. Now, when I manually add new data points to the bottom of this table, I would like to have a load script run that uploads that new data back into BigQuery, and appends it to my original table. I read somewhere that just by inserting a new table the data is automatically appended if the table mentioned already exists. However, I haven't tested that part yet since I get stuck on an error earlier up the line..
Below is the load script I have loosely copied from https://developers.google.com/apps-script/advanced/bigquery
function loadCsv() {
var projectId = 'XX';
var datasetId = 'YY';
var tableId = 'daily_stats_testing';
var file = SpreadsheetApp.getActiveSpreadsheet();
var sheet = file.getActiveSheet().getRange("A12:AK10000").getValues();
var data = sheet.getBlob().setContentType('application/octet-stream');
var job = {
configuration: {
load: {
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: tableId
},
skipLeadingRows: 1
}
}
};
job = BigQuery.Jobs.insert(job, projectId, data);
var Msg = "Load started. Check status of it here:" +
"https://bigquery.cloud.google.com/jobs/%s", projectId
Logger.log(Msg);
Browser.msgBox(Msg);
return;
}
Now the error I get (in a variety of forms, since I've been testing stuff out) is that the BigQuery.Jobs function only accepts Blob data, and that the data from my current sheet (with rage A12 marking the first manually imputed row of data) is not a Blob recognizable data set.
Is there any way (any function?) I can use that will directly convert the selected data range and make it Blob compatible?
Does anyone have any recommendation on how to do this more efficiently?
Unfortunately the script has to load directly out of the current, open Spreadsheet sheet, since it is part of a larger script I will be running. Hopefully this isn't too much of a hinder!
Thanks in advance for the help :)
Is there any way (any function?) I can use that will directly convert the selected data range and make it Blob compatible?
There is actually a function that does convert objects into blob type, namely newBlob(data).
To test this I got a range from my spreadsheet and used it.
function blobTest(){
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A1:C1");
Logger.log(range); //here, range data is of type Range object
var blob = Utilities.newBlob(range);
Logger.log(blob); //here, range data is now of type Blob object
}

How can I pull information from 2 different excel cells on the same worksheet using javascript? I

<script language="javascript" >
function GetData(cell,row){
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("I:Work/database/72550.xls");
var excel_sheet = excel.Worksheets("CA 2012-2013 HMO Plans");
var data = excel_sheet.Cells(cell,row).Value;
document.getElementById('div1').innerText =data;
}
</script>
<input type="button" value="Hearing Services" onClick="GetData(45,2);" />
This is all in a table but I didn't think it was nec to display that, and of course file names are changed. All I need to know is how to pull from two cells at once from the same work sheet to display on a webpage. I got it working put only from one cell. How can I add another cell data to my result text?
is easier to take all the information inside a database, and do a cross join, as you usuing java, i recommend you use oracle, and so a simple cross join, depends on the head text of your excel sheets.
inside your code use odbc connection, you can simple get the connection part if you connect your database inside the sql developer.

Categories

Resources