Reputation: 81
I always get confused on how to properly format json. I think its because I need to walk away and take a breather.
I have a have a ecommerce system and I have a script that I want to display category information via json. Will displaying it this way:
{
"cat_name": "All Items",
"cat_desc": "<div><img src=\"item.gif\" /></div>",
"cat_desc2": "",
"cat_id": "756",
"cat_father_id": "0",
"cat_image": "",
"per_ship": "0.00",
"item_ship": "0.00",
"item_int_ship": 0,
"per_int_ship": "0.00",
"noProducts": "45",
"disp_order": "3",
"cat_img_folder": ""
}
Would I be able to reference these items after being initlized to an object like so:
obj.cat_name
obj.cat_id
Upvotes: 0
Views: 63
Reputation: 13716
That's properly formated, if your service returns that information you could do the following
$.getJSON('YOURSERVICEURL', function(data) {
$.each(data, function(key, val) {
console.log('KEY: ', key, ' VALUE', val );
});
});
where key will be the property and val the value when you access it (in the fashion data[key] === value, or, data.key === value).
So, yes, if data
has the key that you're looking for (in your case cat_name cat_id
, you can get them.
One thing to have in mind is that Numbers doesn't need to be between ""
, if you want them to be numbers when you access them via object properties
Also, if you ever need to know if you're formatting your json correctly you could take a look at this link
Upvotes: 3
Reputation: 4019
Yes, after you run eval or the proper json2 parse function you can access it like you said, and if you ever have issues read the syntax at www.json.org, also there's a site called http://www.jsonlint.com where you can paste your JSON in and test it.
You'll find there's a lot of freedom in JSON, u can have nested objects/arrays and more
Upvotes: 0
Reputation: 5897
Simply... yes, but you have to know that those properties are in the object for sure or you'll get some strangeness.
You can also access them via:
obj[cat_name]
obj[cat_id]
of:
var x;
for(x in obj){
console.log("x:" +x+" - value:"+obj[x]);
}
Upvotes: 0