I am using JavaScript serializer to send value to JavaScript:
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
var Result = (from c in dt.AsEnumerable()
select new
{
Latitude = c.Field<Decimal>("Latitude"),
Longitude = c.Field<Decimal>("Longitude")
}).ToList();
hdnControl.Value = oSerializer.Serialize(Result);
This results in this kind of value:
[
{"Latitude":19.2094000000,"Longitude":73.0939000000},
{"Latitude":19.2244070000,"Longitude":73.1545760000},
{"Latitude":32.5838493257,"Longitude":132.3632812500},
{"Latitude":59.3331894266,"Longitude":8.6572265625}
]
How can I retrieve these values in a JavaScript function?
Are there any inbuilt method to access it
or do I need to use the .split() function to get the values?
Any help will be appreciated.
This is javascript json array. You can use forEach to retrieve the value using the keys
a.forEach(function(item){
document.write('<pre> Latitute is '+item.Latitude+'</pre>')
})
A complete list of of array methods is available HERE which can be used as required
JSFIDDLE
Related
I need to pass a matrix from the C# code behind to javascript, however at the moment when my matrix is passed to the view, it is converted into a single dimensional array. In other words, my multi dimensional array is flattened by the serialization.
C# code
List<leituras> listaleituras = new List<leituras>();
public object[,] arrayTemperatura = new object[5, 3];
public JavaScriptSerializer javaSerial = new JavaScriptSerializer();
foreach (var leitura in listaleituras)
{
arrayTemperatura[i, 0] = leitura.Data.Month.ToString() + "/" + leitura.Data.Year.ToString();
arrayTemperatura[i, 1] = leitura.Sensor_temperatura;
arrayTemperatura[i, 2] = leitura.Sensor_temperatura;
i++;
}
Output
expected output format
[
["09/18",95,95],["10/18",257,257],["11/18",1368,1368],["12/18",1574,1574],
["01/19",2437,2437],["02/19",3105,3105],["1/3",2096,2096],["2/3",1098,1098],
["4/3",361,361],["6/3",1993,1993],["7/3",2744,2744],["8/3",2891,2891],
["9/3",1797,1797],["11/3",3027,3027],["12/3",2996,2996],["13/3",2766,2766],
["14/3",3067,3067],["15/3",3043,3043],["16/3",2374,2374]
]
How do I pass a serialized multi dimensional array?
use JSON.NET
string json_string = JsonConvert.SerializeObject(arrayTemperatura);
it serializes multi-dimension arrays as you want.
then in javascript you can desrialize json using JSON.parse
var multidimentionArray = JSON.parse( json_string );
also see this
Use a jagged array instead of a two-dimensional array.
First of all declare your array without intialising it: public object[][] arrayTemperatura;
then do this after your while loop:
arrayTemperatura = new object[listaleituras.length][];
foreach (var leitura in listaleituras)
{
arrayTemperatura[i] = new object[3];
arrayTemperatura[i][0] = leitura.Data.Month.ToString() + "/"+ leitura.Data.Year.ToString();
arrayTemperatura[i][1] = leitura.Sensor_temperatura;
arrayTemperatura[i][2] = leitura.Sensor_temperatura;
i++;
}
Alternatively you could use the Json.NET serializer instead of the JavaScriptSerializer - I have created an example to show that it just behaves the way you'd expect in your question: https://dotnetfiddle.net/2QBP7J
I want to extract Lat/Long values from the below mentioned array. Please help me.
var products = {"PolygonCords":"[[51.65040675460229,0.034332275390625],[51.613752957501,0.028839111328125],[51.61034179610213,0.1812744140625],[51.642737480428536,0.157928466796875]]"};
Parse the json string using JSON.parse() and iterate over array using forEach
var products = {
"PolygonCords": "[[51.65040675460229,0.034332275390625],[51.613752957501,0.028839111328125],[51.61034179610213,0.1812744140625],[51.642737480428536,0.157928466796875]]"
};
JSON.parse(products.PolygonCords).forEach(function(v) {
console.log(v[0], v[1])
})
How can I change/modify/refresh my localstorage of AngularJS?
My localstorage content is an object json:
//data content: {Id:1,Name:"Juanito"}
localStorageService.set("MyObj",data);
console.log(localStorageService.get("MyObj"));
//SHOW object JSON {Id:1,Name:"Juanito"}
But if I modify a unique key like this:
localStorageService.set("MyObj.Id","otherid"),
It does not work. How do I fix this?
Try retrieving, then updating and re-setting:
var data = {id: 123}
localStorageService.set("MyObj",data);
var dataFromLS = localStorageService.get("MyObj");
dataFromLS.id = 456;
localStorageService.set("MyObj",data);
console.log(localStorageService.get("MyObj"));
When you change/modify your key name, a brand new object will be created/stored in your service.
If you want to change/alter key's data/value, perform intermediate operations and set it with same key.
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];
I have a JSON which lists the values from database. Below is the JSON data of 2 rows from the database.
[{"Name":"P1","Description":"pd1","Value":"v1","Attribute":"a1"},{"Name":"P1","Description":"pd1","Value":"v2","Attribute":"a2"}]
database values are the result of a left join query. Only 'Value' and 'Attribute' fields are different. Can I append that fields to JSON instead of multiple sets of record? I know there is 'push' to do this, but I am unaware where and how to use this in my code. below is the code for fetching values from db and serializing the values.
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);
Below is my getJSON
$(document).ready(function () {
$.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute+' : '+v.Value);
});
});
});
Please help me here.
There are several things you can do.
Store value and attribute as arrays:
[{"Name":"P1","Description":"pd1","Value":["v1", "v2"],"Attribute":["a1", "a2"]}]
Or store them as a 'symbol'-separated string:
[{"Name":"P1","Description":"pd1","Value":"v1;v2"],"Attribute":"a1;a2"]}]
In order to use the first case, you'll have to try and figure out how to format the ProfileDetails in order to have javaScriptSerializer.Serialize parse it correctly. You will likely have to convert your data first in order for this to work (i.e. convert value and attribute to arrays).
For the second case to work you could modify your GetProfileDataService.GetList method so that values and attributes are merged to symbol-separated strings (something like this: GROUP BY to combine/concat a column)