get data from dynamic key value in json - javascript

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

Related

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

JavascriptSerializer.Deserialize & Encoding

I use Vietnamese in input content to an textbox like "ngày 1".
The first time I do Javascript.Serialize an object & put it in array, store in cookie:
class sampleCookie
{
public string tripDate;
}
=>I got right value string is "ngày 1".
Again, I add new record to this list with another string "ngày 2".
=> I got the first record value string is "ngà y 1"
I can't figure out the way to Encoding for it.
What I'm missing?
This's my code
var estCookie = Request.Cookies[inputModel.SampleCookieName];
if (estCookie != null)
{
var serializer = new JavaScriptSerializer();
var serializeModel = serializer.Deserialize<ListSampleCookie>(estCookie.Value);
// I Update string value in here
//Put insert item to list
serializeModel.Add(new SampleCookie
{
TripDate = inputModel.TripDate ,
Memo = inputModel.Memo,
OptionFee = inputModel.OptionFee
});
// Serialize data
var sampleData = serializer.Serialize(serializeModel);
//Update cookie value
estCookie.Value = sampleData;
Response.AppendCookie(estCookie);
}

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)

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

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.

Categories

Resources