MoonKiKi: web2.0 and ajax... the evolution road

Thursday, May 14, 2009

RETRIEVE GIVEN PROPERTY FROM A JSON

Often some user ask me how to retrieve in an elegant way and without using
the function eval, a property from a json, if that property is in a string.
So not to write that:


var param = 'pippo';

var res = eval('json.'+param); //per fare json.pippo

Here my response. Use an utility js where do you put that function
and use it as I display below.
getProps = function(obj, prop) {
for (var i in obj) {
if (i==prop) { alert(obj[i]); return; }

if (typeof obj[i] == "object") {
dumpProps(obj[i], i);
}
}
}

var json = {"pippo":"ciao","pluto":"bao"}
var searchedProps ="pluto"

getProps(json,searchedProps);


In these example I shown an alert for the searched property, but you need to return itn
in that way:


if (i==prop) { return
obj[i] }


So you can notice something that not all newbies know. You can reach a
value by name in the json properties name/value collection.
Because variable "i" is the name of property
given from the for with the keyworld "in".


Do you want something simpler than previous function?
Ok.

Look here:

if (json[searchedProps])
alert(json[searchedProps])

;)

Moonkiki

No comments:

Post a Comment