C# and Javascript Pass DATA - javascript

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)

Related

POSTing a array from android to Google apps script

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]);

How do I programmatically build an object from my form data that includes arrays

I need to display some values on a jsp page, grab input from user and send it back to a controller that is using Jackson to bind it to my backing data object. Several rows that I display on the screen are backed by an array and are created with <c:forEach> and I'm generating a path like "blobs[0].id" and "blobs[0].text". When I try to put them into the json object to be sent back to the controller by an ajax call, they aren't being added to the object properly. The property name ends up having "[0]" in the name instead of representing the object at that array index.
<script>
var formData = {};
formData.blobs = [];
formData.blobs[0] = {};
formData.blobs[0].id = "English";
formData.blobs[0].text = "Hello";
formData["blobs[1].id"] = "German";
formData["blobs[1].text"] = "Guten Tag";
console.log(formData);
</script>
ends up looking like {blobs: [0 : {id: "English", text: "Hello"}], blobs[1].id: "German", blobs[1].text: "Guten Tag"} instead of
{blobs: [0 : {id: "English", text: "Hello"}, 1 : {id: "German", text: "Guten Tag"}]}
I am trying to assemble the model thusly:
<script>
function createModel() {
var form = $("#theForm");
var formData = {};
$.each(form, function(i, v){
var input = $(v);
if (input.attr("name")) {
formData[input.attr("name")] = input.val();
}
});
}
</script>
Accessing obj["attr"] is an option to access an object's attribute, so obj["attr[1][22]"] will access an attribute called "attr[1][22]", while accessing obj["attr"][1][22] will access the second element of obj.attr, and the second element's 22th element as well..
The solution will be to access formData["blobs"][0].id or even formData["blobs"][0]["id"]
you can format the string to your needs
$('#yourform').serializeArray() returns an array:
[
{"name":"foo","value":"1"},
{"name":"bar","value":"xxx"},
{"name":"this","value":"hi"}
]
$('#yourform').serialize() returns a string:
"foo=1&bar=xxx&this=hi"
so, in your case
var formData = {};
formData.blobs = [];
$('#yourform').serializeArray().forEach(function(blob){
formData.blobs.push({
id: blob.name,
text: blob.value
});
})

How to convert Json arrays to integer from string in Java script

In my application I will get a Json string from server (java).
When I retrieve the Json in Java script what I get is
var data = [{"value":"3","label":"17 hr"}
{"value":"2","label":"18 hr"},
{"value":"1","label":"19 hr"}]
}]
What I want is
var data = [{"value":3,"label":"17 hr"},
{"value":2,"label":"18 hr"},
{"value":1,"label":"19 hr"}]
}]
That is value column is retrieved as strings instead of integer values. How to retrieve them as integers? What is the best or optimal way to do the same?
var data = [{"value":"3","label":"17 hr"},
{"value":"2","label":"18 hr"},
{"value":"1","label":"19 hr"}]
// if you want to keep the data var untouched
var parsedData = data.map(function(item) {
// make sure you don't change item's reference by returning new object
return {
value: parseInt(item.value, 10),// you will end up with NaN if item.value is not a number
label: item.label
};
});
// if you don't care about mutation
data.forEach(function(item) {
item.value = parseInt(item.value, 10)
});

How to parse dynamic json data?

I am using wikipedia API my json response looks like,
"{
"query": {
"normalized": [
{
"from": "bitcoin",
"to": "Bitcoin"
}
],
"pages": {
"28249265": {
"pageid": 28249265,
"ns": 0,
"title": "Bitcoin",
"extract": "<p><b>Bitcoin</b>isapeer-to-peerpaymentsystemintroducedasopensourcesoftwarein2009.Thedigitalcurrencycreatedandlikeacentralbank,
andthishasledtheUSTreasurytocallbitcoinadecentralizedcurrency....</p>"
}
}
}
}"
this response is coming inside XMLHTTPObject ( request.responseText )
I am using eval to convert above string into json object as below,
var jsonObject = eval('(' +req.responseText+ ')');
In the response, pages element will have dynamic number for the key-value pair as shown in above example ( "28249265" )
How can I get extract element from above json object if my pageId is different for different results.
Please note, parsing is not actual problem here,
If Parse it , I can acess extract as,
var data = jsonObject.query.pages.28249265.extract;
In above line 28249265 is dynamic, This will be something different for different query
assuming that u want to traverse all keys in "jsonObject.query.pages".
u can extract it like this:
var pages = jsonObject.query.pages;
for (k in pages) { // here k represents the page no i.e. 28249265
var data = pages[k].extract;
// what u wana do with data here
}
or u may first extract all page data in array.
var datas = [];
var pages = jsonObject.query.pages;
for (k in pages) {
datas.push(pages[k].extract);
}
// what u wana do with data array here
you can archive that using two methods
obj = JSON.parse(json)
OR
obj = $.parseJSON(json);
UPDATE
Try this this
var obj = JSON.parse("your json data string");
//console.log(obj)
jQuery.each(obj.query.pages,function(a,val){
// here you can get data dynamically
var data = val.extract;
alert(val.extract);
});
JSBIN Example
JSBIN

get data from dynamic key value in json

The requirement is following:
I have to get the location field from page.
var input= global.input = document.getElementById("Location");
Get the neighborhood area from the json file based on input and show on the page.
I have a json object and have to filter the data from the json object based on the key value (location)
var inputLocation=input.value;
In my javascript I am getting the error if I use dynamic the key.
I am able to get the json array if I do this data.Aspen but i have to get the data from a text field and it can be different so if I call data.inputLocation... its coming undefined
when i use data.(inputLocation.value) getting the following error :
XML filter is applied to non-XML value ({Aspen:[{ID:
{
"Aspen":[
{
"ID":"Bellaire",
"Name":"Bellaire"
},
{
"ID":"Champions Forest",
"Name":"Champions Forest"
},
{
"ID":"Highland Village",
"Name":"Highland Village"
},
{
"ID":"Museum District",
"Name":"Museum District"
}
]
}
You can access the property using array-like syntax:
data[inputLocation]
If inputLocation is set to "Aspen", then it is the same as these two lines:
data["Aspen"]
data.Aspen
get value from dynamic json object Using real time currency converter rest api responce
public async Task<JsonResult> ConvertCurrency(float Price, string FromCurrency)
{
var testcase = FromCurrency + "_USD";
WebClient web = new WebClient();
const string ConverterApiURL = "http://free.currencyconverterapi.com/api/v5/convert?q={0}_{1}&compact=ultra&apiKey={{EnterKey}}";
string url = String.Format(ConverterApiURL, FromCurrency, "USD");
string response = new WebClient().DownloadString(url);
var data = (JObject)JsonConvert.DeserializeObject(response);
dynamic result = data.SelectToken(testcase + ".val").ToString();
var basePrice = float.Parse(result);
double exchangeRate = Price * basePrice;
var responce = Math.Round(exchangeRate, 2);
return Json(responce, JsonRequestBehavior.AllowGet);
}

Categories

Resources