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.

1 response to Iterate over a JSON object

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

Leave a reply

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

* Copy This Password *

* Type Or Paste Password Here *

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=""> <s> <strike> <strong>


Skip to toolbar