0

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
1
  • What you have is a json object (which is also a javascript object), but not a json string. I don't understand which one of the two you are looking for. Commented Feb 3, 2012 at 18:32

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.