...

View Full Version : possible to loop through a JSON object?



Leeoniya
08-28-2007, 08:22 PM
i have a JSON object (w/1 level - (key value pairs)) returned to the client that needs to be used to fill in a form. Is there a way to use a FOR loop to set every value in the key fields?

i have looked for a few hours and it seems like there is no easy way to do it., i cant access the key names except by name or by index, and both of those give me the value, not the key name, and i need both.

thanks,
Leon

liorean
08-28-2007, 08:31 PM
i have a JSON object (w/1 level - (key value pairs)) returned to the client that needs to be used to fill in a form. Is there a way to use a FOR loop to set every value in the key fields?
var
key;
for(key in JSONObject)
if(JSONObject.hasOwnProperty(key)){
/* do something with JSONObject[key] */
}

Beware that Object.prototype.hasOwnProperty does not work in Safari 1.3 (last version that can be used on Mac OS X 10.3 (Panther)). I don't know whether it works in later versions.


If you want a version that is safe for Safari 1.3:
var
key;
for(key in JSONObject)
if(!(key in Object.prototype) || JSONObject[key]!==Object.prototype[key]){
/* do something with JSONObject[key] */
}



WARNING: I haven't actually tried out this code, so it might be buggy.

Kor
08-28-2007, 09:56 PM
liorean, please, why is necessary the Object.prototype? Couldn't a simple loop solve the problem? Or I miss something? I am also interested in modifying a JSON object's key/value in a short manner.... I use to think that prototype and JSON have a not so closed relationship :)

liorean
08-28-2007, 10:03 PM
liorean, please, why is necessary the Object.prototype? Couldn't a simple loop solve the problem? Or I miss something? I am also interested in modifying a JSON object's key/value in a short manner.... I use to think that prototype and JSON have a not so closed relationship :)Because the for(key in obj) syntax will not only walk through all properties on the object, it will also walk through the full prototype chain. So any property on Object.prototype will appear in the loop. Because of that you have to filter out the properties that come from the prototype chain.

Kor
08-28-2007, 10:35 PM
OK, thanks, I'll think about...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum