Access Data from Ajax Call Jquery - javascript

I am using Jquery Ui Autocomplete.
The problem I have is the data that is being returned from my api.
"{"d":{"results":[],"facets":{"facet_counts":{"Town":{"":0,"londonderry":136914,"london bridge":1,"london":8983316,"london colney":1}}},"__solr_time":3473457,"__ser_time":1564,"__t_time":1421,"__count":9120232,"__max_score":1.0}}"
I have run it through an online parser and it is valid, but I don't know how to access the list of towns with the corresponding number next to it.
Any help would be appreciated

I was able to access the Town "name" and number using:
var test = {
"d": {
"results": [],
"facets": {
"facet_counts": {
"Town": {
"": 0,
"londonderry": 136914,
"london bridge": 1,
"london": 8983316,
"london colney": 1
}
}
},
"__solr_time": 3473457,
"__ser_time": 1564,
"__t_time": 1421,
"__count": 9120232,
"__max_score": 1
}
}
for(var prop in test.d.facets.facet_counts.Town){
console.log(prop);
console.log(test.d.facets.facet_counts.Town[prop]);
}

Just run JSON.parse() on the string and then pull out the Town node.
var string; // the data string returned by API.
var dataObj = JSON.parse(string);
var Town = dataObj.d.facets.facet_counts.Town;
// access the properties as needed
var londonCount = Town.london;
var londonBridgeCount = Town['london bridge']; // need to use bracket notation to get this one

Related

How to loop and extract the value of newsid, headline inside a nested JSON string

The Nested JSON - image
{"newsalert":[{"newslist":{"1":{"newsid" :"4321","headline" :"Great White Shark Found","newscode" :"GWS","newstime" :"10:04:32"},"2":{"newsid" :"8031","headline" :"Polar Bear Escaped","newscode" :"PBE","newstime" :"09:28:03"}}}]}
var dt = JSON.parse(json_string);
var value = dt.newsalert[0].newslist.headline;
console.log(value); // Undefined result
I am having a hard time figuring out how to extract the newslist which is inside the array newsalert. Need to extract the properties newsid, headline, newscode.
Thank you :)
Dont know exactly what you are trying to achieve, but this is how you access the properties in json
var a={
"newsalert": [{
"newslist": {
"1": {
"newsid": "4321",
"headline": "Great White Shark Found",
"newscode": "GWS",
"newstime": "10:04:32"
},
"2": {
"newsid": "8031",
"headline": "Polar Bear Escaped",
"newscode": "PBE",
"newstime": "09:28:03"
}
}
}]
}
var value = a.newsalert[0].newslist[1].headline;
console.log(value);

Converting xml request to json request with duplicate node names

I trying to push data to a 3rd party webservice, specifically converting the xml request to a json one (for use with node soap).
Here is an example of the raw xml request that works fine:
<EformData>
<EformFields>
<FieldName>txt_customername</FieldName>
<FieldValue>Scott</FieldValue>
</EformFields>
<EformFields>
<FieldName>txt_organisation</FieldName>
<FieldValue>My Orginisation</FieldValue>
</EformFields>
<EformFields>
<FieldName>txt_address</FieldName>
<FieldValue>My Address</FieldValue>
</EformFields>
<EformFields>
<FieldName>txt_telnumber</FieldName>
<FieldValue>123456</FieldValue>
</EformFields>
</EformData>
The problem i'm having is trying to convert these duplicate nodes into an object, the new object data is being overwritten with the last request.
Here's what i have so far:
var formValues = {
"txt_customername": "Scott",
"txt_organisation": "My Orginisation",
"txt_address": "My Address",
"txt_telnumber": "123456"
}
// Container
var EformData = {
"EformFields": {
}
};
// populate the object
for (var key in formValues) {
EformData.EformFields.FieldName = [key];
EformData.EformFields.FieldValue = formValues[key];
}
As you can see below, only the last request is stored in the object, the others are overwritten:
<EformData>
<EformFields>
<FieldName>txt_telnumber</FieldName>
<FieldValue>123456</FieldValue>
</EformFields>
</EformData>
Is it possible to build an object in such a way to match the orginal duplicate xml node data?
The data structure of your json should be that EformData has an array of EformFields objects, which has the properties of FieldName and FieldValue.
var formValues = {
"txt_customername": "Scott",
"txt_organisation": "My Orginisation",
"txt_address": "My Address",
"txt_telnumber": "123456"
}
// Container
var EformData = {
"EformFields": []
};
// populate the object
for (var key in formValues) {
EformData.EformFields.push({
"FieldName": key,
"FieldValue": formValues[key]
});
}
In your array, only 0th index is populated always and hence it is overrided when on the next iteration add an index for the array iteration as follows
// Container
var EformData = {
"EformFields": [
]
};
// populate the object
int i=0;
for (key in formValues) {
EformData.EformFields[i].FieldName = [key];
EformData.EformFields[i].FieldValue = formValues[key];
i++;
}

How do i iterate through JSON array in javascript?

I have a json data coming from rest in following format:
{
"status_code": 200,
"data": {
"units": -1,
"unit_reference_ts": null,
"tz_offset": -4,
"unit": "day",
"countries": [{"country": "IN", "clicks": 12}]},
"status_txt": "OK"
}
I want to access the countries part and need to generate data in format like
{"IN":12, ......}
I dont know how to iterate through javascript, JSON array? Please help i am confused between methods which is the best & easiest that will work throughout the JSON?
I tried this:
$.each(response.countries, function(key, value) {
console.log(value.country + ": " + value.clicks);});
but it is showing me type error e is undefined...
Make sure you parse your JSON first (var data = JSON.parse(json)), then use a simple loop:
var obj = {};
for (var i = 0, l = data.data.countries.length; i < l; i++) {
var tmp = data.data.countries[i];
obj[tmp.country] = tmp.clicks
}
console.log(obj); // { IN: 12, UK: 123 }
DEMO
Since (from your edit) you're using jQuery, you'll probably need to do this (note that jQuery automatically parses JSON data if you retrieve it using one of its AJAX methods):
var obj = {};
$.each(response.data.countries, function(key, value) {
obj[value.country] = value.clicks;
});
If you want a string instead of an object, just JSON.stringify the obj:
var json = JSON.stringify(obj);
DEMO

Is there a way to iterate and display the list of key value pairs of json using Handlebar.js

As Iam new to javascript, I found handleBar.js can be used to template with dynamic data.
I worked on a sample which worked fine and the json structure was simple and straight forward.
(function()
{
var wtsource = $("#some-template").html();
var wtTemplate = Handlebars.compile(wtsource);
var data = { users: [
{url: "index.html", name: "Home" },
{url: "aboutus.html", name: "About Us"},
{url: "contact.html", name: "Contact"}
]};
Handlebars.registerHelper('iter', function(context, options) {
var fn = options.fn, inverse = options.inverse;
var ret = "";
if(context && context.length > 0) {
for(var i=0, j=context.length; i<j; i++) {
ret = ret + fn($.extend({}, context[i], { i: i, iPlus1: i + 1 }));
}
} else {
ret = inverse(this);
}
return ret;
});
var temp=wtTemplate(data);
$("#content").html(temp);
})();
<script id="some-template" type="text/x-handlebars-template">
{{#iter users}}
<li>
{{name}}
</li>
{{/iter}}
</script>
How to iterate a json with the below structure ? Please do suggest the possible way for iterating and creating the template for the below json structure
var newData = { "NEARBY_LIST": {
"100": {
"RestaurantID": 100,
"ParentRestaurantID": 0,
"RestaurantName": "Chennai Tiffin",
"listTime": [{
"startTime": "10:00",
"closeTime": "23:30"
} ]
},
"101": {
"RestaurantID": 101,
"ParentRestaurantID": 0,
"RestaurantName": "Biriyani Factory",
"listTime": [{
"startTime": "11:00",
"closeTime": "22:00"
}]
}
}
};
Accessing the properties of an object has nothing to do with Handlebars. If you dealing with JSON and you wish to access it in general bracket or dot notation, you must first parse the JSON into a JavaScript object using the JSON.parse() function.
After this is done, you may access the properties as follows.
var property = newData['NEARBY_LIST']['100'].RestaurantName; // "Chennai Tiffin"
Here is a fiddle to illustrate.
http://jsfiddle.net/qzm0cygu/2/
I'm not entirely sure what you mean, but if your question is how you can use/read the data in newData, try this:
newData = JSON.parse(newData); //parses the JSON into a JavaScript object
Then access the object like so:
newData.NEARBY_LIST //the object containing the array
newData.NEARBY_LIST[0] //the first item (key "100")
newData.NEARBY_LIST[1] //the second item (key "101")
newData.NEARBY_LIST[0][0] //the first field of the first item (key "RestaurantID", value "100")
newData.NEARBY_LIST[0][2] //the third field of the first item (key "RestaurantName", value "Chennai Tiffin")
newData.NEARBY_LIST[0][3][0] //the first field of the fourth field of the first item (key "startTime", value "11:00")
I hope this was what you were looking for.
EDIT: as Siddharth points out, the above structure does assume you have arrays. If you are not using arrays you can access the properties by using their names as if they're in an associative array (e.g. newData["NEARBY_LIST"]["100"]. The reason I say "properties" and "as if" is because technically JavaScript doesn't support associative arrays. Because they are technically properties you may also access them like newData.NEARBY_LIST (but I don't recommend that in this case as a property name may not start with a number, so you would have to use a mix of the different notations).
On that note, I would recommend using arrays because it makes so many things easier (length checks, for example), and there are practically no downsides.
EDIT2: also, I strongly recommend using the same camelcasing conventions throughout your code. The way you currently have it (with half your properties/variables starting with capitals (e.g. "RestaurantName", "RestaurantID") and the other half being in lowerCamelCase (e.g. "listTime", "startTime")) is just asking for people (you or colleagues) to make mistakes.

jQuery object get value by key

How would you get the value of assocIMG by key matching the key eg
if I have a var 11786 I want it to return media/catalog/product/8795139_633.jpg
var spConfig = {
"attributes": {
"125": {
"id": "125",
"code": "pos_colours",
"label": "Colour",
"options": [{
"id": "236",
"label": "Dazzling Blue",
"price": "0",
"oldPrice": "0",
"products": ["11148"]
}, {
"id": "305",
"label": "Vintage Brown",
"price": "0",
"oldPrice": "0",
"products": ["11786", "11787", "11788", "11789", "11790", "11791", "11792", "11793"]
}]
}
}
};
var assocIMG = // Added - Removed { here, causes issues with other scripts when not working with a configurable product.
{
11786: 'media/catalog/product/8795139_633.jpg',
11787: 'media/catalog/product/8795139_633.jpg',
}
Above is the objects I am working with and below is my current jQuery. Help would be greatly appreciated.
$('#attribute125').change(function() {
var image = $(this).val();
$.each(spConfig.attributes, function() {
prods = $(this.options).filter( function() { return this.id == image; } )[0].products[0];
alert(prods);
});
});
You can use bracket notation to get object members by their keys. You have the variable prods containing a string ("11786"), and the object assocIMG with various keys. Then just use
assocIMG[prods]
to get the property value 'media/catalog/product/8795139_633.jpg' which is associated with that key.
Note that you should always use strings as keys in your object literal, IE does not support numbers there:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg'
};
Another improvement to your script would be not to loop through the spConfig.attributes each time, and potentially execute your action multiple times if an image is contained in more than one attribute. Instead, build a hash object out of it, where you can just look up the respective product id.
var productById = {};
$.each(spConfig.attributes, function() {
$.each(this.options, function() {
var id = this.id;
productsById[i] = this.products[0];
});
});
$('#attribute').change(function() {
var id = this.value;
var prod = productById[id];
var image = assocIMG[prod];
$("#product_img").attr("src", image);
});
You should not use numbers as object keys (in their start). If you want to get the value associated with the 11786 integer key, you will need to use this syntax:
assocIMG["11786"] or assocIMG[11786]
Not
assocIMG.11786
The first thing that you need to do is to create your keys as strings, since you would have:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg',
}
But even doing this, you won't be able to access the field using assocIMG.11786 and the first valid sintax that I presented will still work. The correct approach would be:
var assocIMG = {
id11786: 'media/catalog/product/8795139_633.jpg',
id11787: 'media/catalog/product/8795139_633.jpg',
}
Or
var assocIMG = {
"id11786": 'media/catalog/product/8795139_633.jpg',
"id11787": 'media/catalog/product/8795139_633.jpg',
}
Note that the keys are now starting with letters, not numbers. And now, you will can access the 11786 field as assocIMG.id11786 or assocIMG["id11786"], not assocIMG[id11786]
To Get the Value from object by matching key I ended up with the following
$.each(assocIMG, function(index, value) {
if(index == prods) {
var image_path = value;
$("#product_img").attr("src", image_path);
//alert(image_path);
}

Categories