Social Icons

twitterfacebookgoogle pluslinkedinrss feedemail

Wednesday, June 3, 2009

Iterating over JSON data

JSON is pretty powerful when working in web pages because as a hash, it gives you all the benefits of say, a C struct (namely grouping [unrelated] data, but you can declare it on the fly and you can add/remove to/from it on the fly.

Let's say I have the following Javascript JSON object (I used strings as the values but they could be anything: objects, functions, etc...):
var f = {
  foo: 'bar1',
  bar: 'bat1',
  bat: 'baz1'
};

The call f.foo would return the string 'bar1' (sans quotes).

But, what if you have a JSON object and you want to iterate over all the values, but you don't know all the keys? The following will generate an alert box for each key/value pair but the alert is simply used to show the results and any type of processing could be done instead:
for (item in f) {
  alert(item + ', ' + f[item]);
}
  
NB: Two major caveats:
  1. Because of namespace pollution by, shall we say, less than kosher JavaScript APIs, you can get whamboozled here through JavaScript's allowance of the prototype operator in that items can be magically added to your hash without your knowledge.

    While this is a bug (not a flaw as some websites state) in JavaScript, the onus is on the developer to ensure they don't pollute the namespace with their code. jQuery is very good about this by ensuring that everything is encapsulated so no pollution occurs.

  2. As it is a hash, we are NOT guaranteed the order over which items will be iterated. This can easily be mitigated by using an array to store the keys separately and then iterate over the array to get the correct order. It should be noted that in this case, we can retrieve the length of the hash via the lenth field on the array and thus, don't need the for-in loop.
Fortunately, the fix for this is simple. We simply change the above block to:
for (item in f) {
  if (f.hasOwnProperty(item)) {
    alert(item + ', ' + f[item]);
  }
}
  
This ensures that we only read items that we placed in the hash - we, unfortunately, still iterate over items that are not ours.

0 comments:

Post a Comment