views:

70

answers:

3

I have a javascript function create(tagName, options) and the options variable is a JSON object. like this:

{id: 'test_id', class: 'test_class'}

I would like to know how to get the 'id/class' part of the json object. Hope you can help!

+5  A: 

You can use dot or square bracket notation:

var obj = {id: 'test_id', klass: 'test_class'};
alert(obj.id + ' ' + obj.klass);

or:

var obj = {id: 'test_id', klass: 'test_class'};
alert(obj['id'] + ' ' + obj['klass']);

You can use a for...in loop to get the keys, e.g.:

var obj = {id: 'test_id', klass: 'test_class'};
for(key in obj) {
    alert(key);   
}​

​ Demo: http://jsfiddle.net/2p2gw/5/

karim79
Be aware that `class` is a *future reserved word*, and some implementations may throw a `SyntaxError` exception if used as an `Identifier`. Safari is a good example, the demo will not work.
CMS
@CMS - I know this (but thanks). I actually commented under the question. I will change to 'klass'.
karim79
A: 
options.id
options.class
Bobby Jack
A: 

In addition to the other examples, you can get the properties out using the object[...] syntax:

options["id"]
options["class"]

Also watch out with your example JSON. To be strictly valid JSON there should be quotes around the keys:

 { "id": "test_id", "class": "test_class" }
Douglas
thanks for the tip
errorhandler