开发者

prototype JSON to Object

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.


You can use a regular for loop for that:

for(var key in obj.col1.combodata) {
    var combo_obj = obj.col1.combodata[key];
    ...
}


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.


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
}


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜