2

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.

4
  • 1
    Just be aware that class is a reserved word in ECMAScript spec. Nothing will break yet since it is not reserved yet in implmentation, but it is a good idea to put the keys in quotes as well. {'id': 'test_id', 'class': 'test_class'} Commented Aug 26, 2010 at 23:49
  • @Chetan - agreed. Recommendation: use klass instead of class. Commented Aug 26, 2010 at 23:50
  • sorry just realized. I don't want the value, I want the actual id bit (I want to be able to pass in anything to as a JSON Object). Sorry for not being clear. Commented Aug 26, 2010 at 23:53
  • 1
    What you have is a JavaScript object literal. It isn't a valid JSON representation. JSON-encoded objects always have the quotes around their member names, and both these and other strings in JSON always use double quotes. Commented Aug 27, 2010 at 1:48

3 Answers 3

5

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/

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

2 Comments

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 - I know this (but thanks). I actually commented under the question. I will change to 'klass'.
0
options.id
options.class

Comments

0

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" }

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.