POSTing a array from android to Google apps script - javascript

I am trying to send an array to google script to put into google sheets.
What I have for the google script:
function insert(e, sheet) {
//var scannedData = e.parameter.sOrder;
var scannedData = JSON.parse(e.parameter.sOrder);
var orderLocation = e.parameter.sLocation;
var d = new Date();
var ctime = d.toLocaleString();
sheet.appendRow([scannedData, orderLocation, ctime]);
return ContentService
.createTextOutput("Success")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
the results it gives me is:
[Ljava.lang.Object;#5c0b25d1 Shipping 25/07/2020, 22:32:21
what it should give me is:
0152502243 Shipping 24/07/2020, 18:20:37
my code on my apps side:
postDataArray = new JSONArray(Arrays.asList(finalData));
postDataParams.put("sOrder", postDataArray);
postDataParams.put("sLocation",orderLocation);
postDataParams.put("sheetName",sheetName);
Log.e("params",postDataParams.toString());
finalData is a String[] that consists of 2 entries.
"Location"
"Data"
if i send finalData[0] as a control then it picks up the first entry, but it gives me this error instead:
[Ljava.lang.Object;#5c0b25d1
The google script needs to take either an array straight or convert a string into an array, and I am stuck on this conversion.
so google script must take the array
finalData = {"Location","Data"}
and convert it into:
[Location]
[Data]

When sending and receiving structured data, it is preferable to send and receive as json.
Sheet#appendRow accepts a single argument of type array. This array should not be a nested array. Try
sheet.appendRow(scannedData);
or
sheet.appendRow([...scannedData, orderLocation, ctime]);
or
sheet.appendRow(scannedData.concat([orderLocation, ctime]);

Assuming a doPost(e)
doPost(e) {
...
var scannedData = e.parameter.sOrder;
var arr ="{"+ scannedData+"}";
var orderLocation = e.parameter.sLocation;
var d = new Date();
var ctime = d.toLocaleString();
var ss=SpreadsheetApp.openById('ssid')
var sheet=ss.getActiveSheet();
sheet.appendRow([arr,ctime]);

Related

Incorrect Range Height - Google Apps Scripts

I am currently trying to get grab values from another spreadsheet and then paste it into a destination spreadsheet. The problem I am running into is that I am getting incorrect range height and incorrect range widths when I run this code. I read something about 2d arrays but I believe I already have a 2d array here to paste to the spreadsheet. Thank you for your time.
function GmailToDrive_StaticTest(gmailSubject, importFileID){
var threads = GmailApp.search('subject:' + gmailSubject + ' -label:uploaded has:attachment'); // performs Gmail query for email threads
for (var i in threads){
var messages = threads[i].getMessages(); // finds all messages of threads returned by the query
for (var j in messages){
var attachments = messages[j].getAttachments(); // finds all attachments of found messages
var timestamp = messages[j].getDate(); // receives timestamp of each found message
var timestampMinusOne = new Date(timestamp.getTime() - (86400000)); // sets the received timestamp to exactly one day prior (# in milliseconds)
var date = Utilities.formatDate(timestampMinusOne, "MST", "yyyy-MM-dd"); // cleans the timestamp string
for (var k in attachments){
var blobs = {
dataType: attachments[k].getContentType(), // retrives the file types of the attachments
data: attachments[k].copyBlob(), // creates blob files for every attachment
fileName: attachments[k].getName()
};
var tempFile = DriveApp.createFile(blobs.data.setContentType('text/csv')).setName(blobs.fileName.split("-", 1).toString() + date); // creates csv files in drive's root per blob file
var tempFileConverted = Drive.Files.copy( {}, tempFile.getId(), {convert: true} ); // converts created files to gsheets
var importData = {
file: tempFileConverted,
ID: tempFileConverted.getId(),
Sheet1: SpreadsheetApp.openById(tempFileConverted.getId() ).getActiveSheet(),
Sheet1_Values: SpreadsheetApp.openById(tempFileConverted.getId() ).getActiveSheet().getDataRange().getValues()
};
tempFile.setTrashed(true);
var importData_Sheet1_Rows = importData.Sheet1.getMaxRows(); - 2;
var importData_Sheet1_Columns = importData.Sheet1.getMaxColumns(); - 2;
var destSheet = SpreadsheetApp.openById(importFileID).getSheets()[0];
destSheet.clearContents();
Logger.log(importData.Sheet1_Values)
destSheet.getRange(1, 1, importData_Sheet1_Rows, importData_Sheet1_Columns).setValues(importData.Sheet1_Values);
DriveApp.getFileById(importData.ID).setTrashed(true);
}
}
}
}
getMaxRows() and getMaxColumns() return the maximum number of column and rows in a sheet, while getDataRange().getValues() return all the values in a sheet that contain data .
So, unless all the cells in a sheet have data the dimensions won't match !
The best you could do is to get the actual size of the data array and use that to set the range for the values in the destination sheet.
It goes (more) simply like this :
destSheet.getRange(1, 1, importData.Sheet1_Values.length, importData.Sheet1_Values[0].length).setValues(importData.Sheet1_Values);
you don't need the other values for rows and columns, just ignore that in your script.

how can i convert my data in javascript server side to json object and array?

i'm working with xpages and javascript server side i want to convert the fields in format json then i parse this dat and i put them in a grid,the problem is that these fields can contains values :one item or a list how can i convert them in json ?
this is my code :
this.getWFLog = function ()
{
var wfLoglines = [];
var line = "";
if (this.doc.hasItem (WF.LogActivityPS) == false) then
return ("");
var WFLogActivityPS = this.doc.getItem ("WF.LogActivityPS");
var WFActivityInPS = this.doc.getItem ("WFActivityInPS");
var WFActivityOutPS = this.doc.getItem ("WFActivityOutPS");
var WFLogDecisionPS = this.doc.getItem ("WF.LogDecisionPS");
var WFLogSubmitterPS = this.doc.getItem ("WF.LogSubmitterPS");
var WFLogCommentPS = this.doc.getItem ("WF.LogCommentPS");
var WFLogActivityDescPS = this.doc.getItem ("WF.LogActivityDescPS");
var Durr =((WFActivityOutPS-WFActivityInPS)/3600);
var json= {
"unid":"aa",
"Act":WFLogActivityPS,
"Fin":WFActivityOutPS,
"Durr":Durr,
"Decision":WFLogDecisionPS,
"Interv":WFLogSubmitterPS,
"Instruction":WFLogActivityDescPS,
"Comment":WFLogCommentPS
}
/*
*
* var wfdoc = new PSWorkflowDoc (document1, this);
histopry = wfdoc.getWFLog();
var getContact = JSON.parse(histopry );
*/ }
Careful. Your code is bleeding memory. Each Notes object you create (like the items) needs to be recycled after use calling .recycle().
There are a few ways you can go about it. The most radical would be to deploy the OpenNTF Domino API (ODA) which provides a handy document.toJson() function.
Less radical: create a helper bean and put code inside there. I would call a method with the document and an array of field names as parameter. This will allow you to loop through it.
Use the Json helper methods found in com.ibm.commons.util.io.json they will make sure all escaping is done properly. You need to decide if you really want arrays and objects mixed - especially if the same field can be one or the other in different documents. If you want them flat use item.getText(); otherwise use item.getValues() There's a good article by Jesse explaining more on JSON in XPages. Go check it out. Hope that helps.
If an input field contains several values that you want to transform into an array, use the split method :
var WFLogActivityPS = this.doc.getItem("WF.LogActivityPS").split(",")
// input : A,B,C --> result :["A","B","C"]

C# and Javascript Pass DATA

My C# application provides the data and send it to a WebService, like this :
list.Add('cool'); //add value to the list
list.Add('whau'); //add value to the list
Service.sendList(list.ToArray()); //send list to the WebService called Service using the WebMethod sendList()
and the way I retrieve this data through a WebService in a Javascript function is like this :
WebService.getList(OnSucceeded,OnFailed);
function OnSucceeded(result){
var data = result[0]; //result[0] = 'cool';
var data2 = result[1]; //result[1] = 'whau';
}
function OnFailed(result){
//do nothing
}
Now, I need my var data like this :
var data = [['january', 2,3],['february', 3,5],['march', 5, 10]];
How I need to send it from C# to the WebService in order to have at the end a var data like just above ?
Thanks for your help !
You will need to send the data as a two-dimensional array.
var list = new List<List<string>>();
list.Add(new List<string>());
list[0].Add("january");
list[0].Add("2");
list[0].Add("3");
...
Service.sendList(list.ToArray());
Or, more succinctly, like this:
var list = new List<List<string>>();
list.Add(new List<string>(new string[] { "february", "3", "5" }));
...
Service.sendList(list.ToArray());
And of course, you can always parse the integers in JavaScript as follows:
parseInt(data[0][1], 10); // parses "2" into 2 (base 10)

Parse json array using javascript

I have a json arry
var students = {"apResults":[{"offid":"267","item_name":"","offer_name":"fsdfsf","stlongitude":"77.5945627","stlatitude":"12.9715987"},
{"offid":"265","item_name":"","offer_name":"vess offer shops","stlongitude":"","stlatitude":""},
{"offid":"264","item_name":"","offer_name":"vess ofer shop","stlongitude":"","stlatitude":""},
{"offid":"263","item_name":"","offer_name":"ofer frm vess","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"262","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"261","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"260","item_name":"","offer_name":"offer1","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"259","item_name":"","offer_name":"offer","stlongitude":"77.5943760","stlatitude":"12.9716060"}]}
How i can parse this json arry using json.parse. I have tried this code
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults);
var offid = contact.offid;
alert(offid)
}
But its giving an error JSON.parse: unexpected character.Edited my question
That's not a json string, that's a regular javascript variable:
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults[i].offid);
alert(contact)
}
JSON parses strings, not objects/arrays.
why need parsing when you can access it like students.Maths[i].Name
students is not a JSON array, it's an actual array. You don't have to parse because it's not a string. So you can access directly to the data you need:
for(i=0;i<students.Maths.length;i++) {
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
You can't parse students because is not a JSON. It's simple object.
However this will work:
var students = JSON.stringify(students); // if you want to send data
students = JSON.parse(students); // after receiving make a object from it
//use like any object
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
Of course it doesn't make sense to write it that way unless you send students data to other site or program.
Edit:
You don't need JSON in this code at all. But if you want to test JSON.parse() do it this way:
var students = { ... } // your data
var students = JSON.stringify(students); // students is `object`, make it `string`
students = JSON.parse(students); // now you can parse it, `students` is object again
for(i=0;i<students.apResults.length;i++) {
var contact = students.apResults; // no JSON
var offid = contact.offid;
alert(offid)
}
That should work.
What you have is a javascript object. So, you won't need the JSON.parse
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i]);
var fullname = contact.Name;
alert(fullname)
}
this should be ok
The idea of JSON is for the exchange of objects represented as a structured string (in a nutshell). What you've got there is simply an object. It's unnecessary (and impossible) to parse and object that isn't JSON into a javascript object; what you have is the outcome of what you would expect from a parsed JSON string.

How to use OpenLayers with MapGuide source

Basically I want the following example http://openlayers.org/dev/examples/mapguide.html to worj against this WMS datasource "http://gis.aarhus.dk/mapguide/mapagent/mapagent.fcgi?USERNAME=Anonymous&";
All I have done so far is changing the url.
var url = "http://gis.aarhus.dk/mapguide/mapagent/mapagent.fcgi?USERNAME=Anonymous&";
I found the following online docs http://dev.openlayers.org/docs/files/OpenLayers/Layer/MapGuide-js.html but I dont know where to get the correct values for these parameters.
var metersPerUnit = 111319.4908; //value returned from mapguide
var inPerUnit = OpenLayers.INCHES_PER_UNIT.m * metersPerUnit;
OpenLayers.INCHES_PER_UNIT["dd"] = inPerUnit;
OpenLayers.INCHES_PER_UNIT["degrees"] = inPerUnit;
OpenLayers.DOTS_PER_INCH = 96;
var extent = new OpenLayers.Bounds(-87.764987, 43.691398, -87.695522, 43.797520);
var tempScales = [100000, 51794.74679, 26826.95795, 13894.95494, 7196.85673, 3727.59372, 1930.69773, 1000];
var params = {
mapdefinition: 'Library://Samples/Sheboygan/MapsTiled/Sheboygan.MapDefinition',
basemaplayergroupname: "Base Layer Group"
};
How do I get the correct values for the above parameters?
You should be able to get information about WMS from GetCapabilities request that in your case should look like this:
http://gis.aarhus.dk/mapguide/mapagent/mapagent.fcgi?USERNAME=Anonymous&REQUEST=GetCapabilities&SERVICE=WMS&VERSION=1.1.1

Categories

Resources