Iterating over JSON object - javascript

I'm having some troubles iterating in a json object.
I'm currently saving the table properties of a some web page in a cookie.
The value of the cookie is an array of objects which I serialize.
The typical value of an array with 2 entries is something like:
cookieValue=["{ "PageID": "1391", "PageSize": "100"}", "{ "PageID": "2341", "PageSize": "50"}"]
My problem is iterating in this array now. I want to be able to check if there is any duplicate entry to update its PageSize (if applicable) or to read it in order to set the page size when a user goes back to the same page.
I've tried this so far:
for (var key in cookieValue) {
if(cookieValue.hasOwnProperty(key) ){
console.log(key + " -> " + cookieValue[key]);
}
}
which give me an output like:
0 -> { "PageID": "1391_tabela", "PageSize": "100"}
1 -> { "PageID": "1391_tabela", "PageSize": "50"}
2 -> { "PageID": "1391_tabela", "PageSize": "10"}
My question is how am i able to access the value of PageID in each entry.
Thanks in advance

I am not sure if I understand you correctly but I think you should just use
cookieValue[key]["PageID"]
together:
for (var key in cookieValue) {
if(cookieValue.hasOwnProperty(key) ){
console.log(key + " -> " + cookieValue[key] + " -> " + cookieValue[key]["PageID"]);
}
}

It seems that you need to get the object by the PageId. Here is a function
function getPageById(pageId) {
for (var pageObj in cookieValue) {
if (pageObj.PageId === pageId)
return pageObj;
}
}

If you only want to access the value of PageId in each entry, you can view example here :
var cookieValue=[{ "PageID": "1391", "PageSize": "100"}, { "PageID": "2341", "PageSize": "50"}];
for (key in cookieValue) {
alert(cookieValue[key]["PageID"]);
}
JSFIDDLE

Manipulate the data using a javascript array for easier code.
One way that should work for you:
convert your JSON into a javascript array using:
var mycookieArray = JSON.parse(cookieValue);
Iterate through it with:
for(String s : myCookieArray)
{
console.log(s.PageID);
}

Related

Get a JSON Key based off of a user select

I am currently creating a tool that allows users to put in their state and category to see what the 3 price plans are. These 2 selections (state/category) will be picked via select field, and the data containing these numbers is in a JSON file:
[{
"Alabama/Category1/Price1":"$123,123 ",
"Alabama/Category1/Price2":"$123,123 ",
"Alabama/Category1/Price3":"$123,123 ",
"Alabama/Category2/Price1":"$345,345 ",
"Alabama/Category2/Price2":"$345,345 ",
"Alabama/Category2/Price3":"$345,345 ",
"Alabama/Category3/Price1":"$456,789 ",
"Alabama/Category3/Price2":"$456,789 ",
"Alabama/Category3/Price3":"$456,789 ",
"Alabama/Category4/Price1":"$321,321 ",
"Alabama/Category4/Price2":"$321,321 ",
"Alabama/Category4/Price3":"$321,321 ",
"Alaska/Category1/Price1":"$123,123 ",
"Alaska/Category1/Price2":"$123,123 ",
"Alaska/Category1/Price3":"$123,123 ",
"Alaska/Category2/Price1":"$345,345 ",
"Alaska/Category2/Price2":"$345,345 ",
"Alaska/Category2/Price3":"$345,345 ",
"Alaska/Category3/Price1":"$456,789 ",
"Alaska/Category3/Price2":"$456,789 ",
"Alaska/Category3/Price3":"$456,789 ",
"Alaska/Category4/Price1":"$321,321 ",
"Alaska/Category4/Price2":"$321,321 ",
"Alaska/Category4/Price3":"$321,321 ",
}]
Basically on button click, I would like to loop through the JSON file and get the State/Category based off the users selections. Being that there are some "/"'s in that key path, I tried stashing the users selection in a variable, so that I could target each price point and display them on the page. My way of trying that was stashing it in a variable like so:
var test = stateSelected + '/' + categorySelected + '/Price1';
This, however does not work, and was wondering if there was any additional insight as to how to achieve this? Reading some other material, it seems some are recommending to use $.parseJSON, but that was not working either. For that I used:
$.getJSON("json_data.json", function(obj) {
$.each($.parseJSON(data), function(key, value) {
//code here
});
});
Sorry for the longevity on this, but too many times on this site I have seen people not give enough information for people to be able to understand the real issue, and I hope I have outlined mine correctly. Any help on this would be appreciated. Thanks!
EDIT: Also, if you think there is a different way to present the JSON data other than the way I have it here, let me know. The data will be updated via spreadsheet and I used an Excel -> JSON translator tool and this was the way it spit back out the data.
I'd format the JSON in the following way:
var options = {
Alabama: {
Category1: {
Price1: "$123, 123",
Price2: "$123, 123",
}
}
}
and then:
var priceOptions = options[stateSelected][categorySelected];
If you cannot alter the JSON then you'll have to iterate through each key in the object:
function getPricePoints(state, category, onComplete)
{
$.getJSON("json_data.json", function(obj)
{
var result = {};
for(key in obj)
{
if(obj.hasOwnProperty(key) && key.indexOf(state + "/" + category + "/") == 0)
{
result[key] = obj[key];
}
}
onComplete(result);
});
}
If you can alter the way the JSON is represented then why not store the data like so:
var options = {
"Alabama/Category1" : {
"Price1":"$123,123 ",
"Price2":"$123,123 ",
"Price3":"$123,123 "
},
"Alabama/Category2" : {
"/Price1":"$345,345 ",
"Price2":"$345,345 ",
"Price3":"$345,345 "
}
...
}
Then you get slash the user's inputs and get all the prices options for that combination of state and category?
test = stateSelected + '/' + categorySelected;
var priceOptions = options[test];

Get the number of parent objects in a json object using jquery

Following is the JSON array, I want to get number of parent objects and then run for loop on them to get each object value.
It should give total count 2 as I have two parent objects - canvas0 and canvas1.
{"canvas0":
"{"objects":
[{"type":"textbox","originX":"left","originY":"top","left":40,"top":350,"width":200,"height":20.97,"fill":"black","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"ADDRESScanvasPage1","fontSize":16,"fontWeight":"normal","fontFamily":"Helvetica","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"center","textBackgroundColor":"","styles":{},"minWidth":20}],"background":""}"
,"canvas1":"{"objects":[{"type":"textbox","originX":"left","originY":"top","left":40,"top":350,"width":200,"height":20.97,"fill":"black","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"ADDRESScanvasPage2","fontSize":16,"fontWeight":"normal","fontFamily":"Helvetica","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"center","textBackgroundColor":"","styles":{},"minWidth":20}],"background":""}"}
As everyone said, your JSON is invalid. The same valid JSON in minimal would look like the following.
var json = {
"canvas0": {
"objects": [
{
"type": "textbox",
"originX": "left"
}
],
"background": "#000"
},
"canvas1": {
"objects": [
{
"type": "select",
"originX": "right"
}
]
}
};
To be able to iterate thru, you don't need the count of top level keys. And moreover, a JSON object doesn't have the length property. All you need to do is, use for...in loops and display the key/values accordingly. Here is an example of how you can do it. Bear in mind that this only works with your specific case as the loop needs changing as and when the JSON levels change.
alert ( "Length of top level keys: " + Object.keys(json).length );
for (var key in json) {
var canvas = json[key];
for (var key2 in canvas) {
if (canvas[key2] instanceof Array) {
var object = canvas[key2][0];
for (var key3 in object) {
alert (key3 + ": " + object[key3]);
}
} else {
alert (key2 + ": " + canvas[key2]);
}
}
}
Here is a working demo with the complete code.

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.

How to loop through JSON file using jQuery

I am trying loop through the following JSON file below:
{
"statements": [{
"subject": "A"
}, {
"predicate": "B"
}, {
"object": "C"
}, {
"subject": "D"
}, {
"predicate": "E"
}, {
"object": "F"
}]
}
As you can see, there are two subjects, two predicates and two objects. I would like to get, for instance, the value "predicate":"E". How can I do this using jQuery or D3 Javascript library. My code below retrieves the first subject "subject":"A".
$.each(data.statements[0], function(i, v){
console.log(v.uriString);
});
or in D3 (I do not know how to do this in D3):
d3.json("folder/sample.json", function(error, graph)
{ // Code is here for getting data from JSON file }
Could anyone please help me loop through the JSON file above and retrieve some particular data either with jQuery or D3 Javascript. Thank you for your help in advance.
Try this:
$(data.statements).each(function (i) {
var d = data.statements[i];
$.each(d, function (k, v) { //get key and value of object
$("body").append("<p>"+k + ":" + v+"</p>");
});
})
Fiddle here.
The reason why your code returns the first item is beacuse you selected it with data.statments[0] and afterwards loop over that one item.
With jQuery you can use the grep-method like this:
var arrayWithItem = jQuery.grep(data.statements, function( obj ) {
return obj.predicate == "E";
});
You can read more about the grep-method here
With D3js I'm not sure, I guess you have to loop through it with an if-statement.

How can I divide this jQuery data array?

I have the following javascript array:
[{
"id": "115",
"poster": "809",
"post": "alfa"
}, {
"id": "127",
"poster": "808",
"post": "beta"
}]​
What do I need to do in order to extract the values into usable variables?
Try this,
var arr = [{"id":"115","poster":"809","post":"alfa"},{"id":"127","poster":"808","post":"beta"}];
for (i = 0; i < arr.length; i++)<br/>
document.write("id: " + arr[i].id + " poster: " + arr[i].poster + " post: " + arr[i].post + "<br/>");
What you have is an array with two elements
data = [a,b]
where both elements a and b are objects each having three fields (id,poster,post).
Recall that to access an element in the array at position i you simply write data[i] (this will access the ith element in your array i.e. one of the objects).
In order to access a field of the object a you simply use a.fieldName. For example a.id will access id field of object a. If you combine them both you can get data[i].fieldName to access field of specific object (for example data[0].id will return "115").
As a side note, array structures are iterable:
for(var i = 0;i<data.length;i++){
id = data[i].id;
post = data[i].post;
poster = data[i].poster;
document.write(id+" "+post+" "+poster+"<br/>");
}
UPDATE: Example on jsFiddle

Categories