errorhandler
errorhandler

Reputation: 157

How do I fetch the attributes/values from JSON using Javascript?

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.

Upvotes: 2

Views: 325

Answers (3)

karim79
karim79

Reputation: 342795

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/

Upvotes: 5

Douglas
Douglas

Reputation: 37781

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

Upvotes: 0

Bobby Jack
Bobby Jack

Reputation: 16048

options.id
options.class

Upvotes: 0

Related Questions