views:

35

answers:

4

Hi,

The following is part of a JSON string returned from the server:

{
  col1: { 
          caption: 'Workspace',
          combodata: {
                       c_0: {
                              id: 0,
                              value: 'Filter...'
                            },
                       c_1: {
                              id: 1, 
                              value: 'Tax'
                            },
                       c_2: {
                              id: 2, 
                              value: 'HR'
                            }
                      }
        }
}

After eval, I can access .caption, and .combodata is visible in Firebug as an object, with c_0 and c_1 visible as objects inside .combodata, with id and value in both c_0 and c_1.

How do I step through each object in .combodata? I tried .combodata.each(c), but that throws an exception. I won't know the names of the objects in .combodata during run time.

+3  A: 

You can use a regular for loop for that:

for(var key in obj.col1.combodata) {
    var combo_obj = obj.col1.combodata[key];
    ...
}
Tatu Ulmanen
+1  A: 

if

var result = {col1: { caption: 'Workspace',combodata: {c_0: {id: 0,value: 'Filter...'},c_1: {id: 1, value: 'Tax'},c_2: {id: 2, value: 'HR'}}}};

then

for ( i in result.col1.combodata ) {
    var item = result.col1.combodata[i];
    //Do stuff with item
}
clarkf
+1  A: 

Can I suggest that you do not eval() the JSON that's returned? What you should be doing is:

var jsondata = { ... };
var obj = JSON.parse(jsondata);

The reason is because eval'ing a string can be dangerous. Imagine if your JSON data looked like this:

"{ some json data here }; alert(document.cookie)"

When you eval that, the users cookie is displayed to them. Now think what happens if instead of alert, that cookie is posted to an attackers URL. They now have access to that users account if such exists.

Josh Smeaton
`JSON.parse` is not available in older browsers; you should consider including the json2 library (http://json.org/json2.js) if you want to support these browsers.
Matt
In this case, the data returned describes the structure of a grid to be created with JScript and would never contain malicious code. Generally speaking, of course, you are correct.
Corne Beukes
A: 

I have found the following to work as well and will use this:

Object.values(col1.combodata).each(function(c2) {
          id = c2.id;
});
Corne Beukes