Wednesday, November 5, 2014

In Javascript how to iterate over the properties of a JSON object?

When you are working with javascript and JSON you may have faced situations where you need to iterate over the properties of a JSON object.
For an example assume that you receive a JSON response for a http request. Think that you don't know the properties of the object. In such a case you may need to iterate over the properties of the JSON response to get the properties and corresponding values.
There are several ways to do this. But you can do this easily by converting the JSON object in to a javascript.

I will show that below.
Since I need a JSON object for this example I create a JSON objcet by using JSON.stringify() method. The name of my JSON object is jsonObj.

var jsonObj = JSON.stringify({name:'John', age:18});

Ok, now we have a JSON object and lets start.
In order to iterate over the properties you first need to convert the JSON object in to a javascript object as below.

var javascriptObj = JSON.parse(jsonObj);

Now you can iterate and access the properties and values as below.

for (var prop in javascriptObj) {
   alert(prop);//property
   alert(javascriptObj[prop]);//value
}

No comments:

Post a Comment