Iterate over a JSON object

February 29, 2012 in JavaScript, Web 2.0

One of the most useful advantages of the JSON format is that it is browser friendly. You donot need to write complicated code for navigating or iterating over a JSON structure. In this post, I will show you how to iterate over a JSON object.

Assume that you are having the following JSON object.

<script type="text/javascript">
var personStr = "{\"Name\":\"Hazem Saleh\",\"Occupation\":\"Software Engineer\",\"Nationality\":\"Egyptian\",\"Age\":\"102\"}";

var personObject = eval("(" + personStr + ")");
</script>

You may notice that I put the JavaScript String between parentheses. This is mandatory to avoid the json invalid label browser error.

if you want to simply iterate over the JSON object you should use the standard JavaScript for in loop as follows.

<script type="text/javascript">
for (var key in personObject) {
  if (personObject.hasOwnProperty(key)) {
    alert(key + " -> " + personObject[key]);
  }
}
</script>

I wish that this tip can be helpful to you.

One comment on “Iterate over a JSON object

  1. Pieter on said:

    Just what I was looking for, my thanks is great!

Leave a reply

Your email address will not be published. Required fields are marked *

294,491 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweet Captcha