HomeBlogProjects

Other Blog Entries


Simple Object Parser

This is a very simple function I use for debugging. It can also be used to convert objects into JSON strings. Console log on FireBug is fabulous, but if you feed it an object, it usually just returns object. What this function does is take that object, or array, or any other type of variable and converts it to a json string and outputs it to the console. For instance, if you want to get the value of a variable, you would just do

o2s(myvar);

multiple variables:

o2s([myvar1,myvar2]);
o2s([myobj,myarr]);

It's small enough that I can just post it here
o2s=function(o){//Simple object parser
ostr="";
function getO(o){
switch(typeof o){
case "undefined": case "function":
ostr += "'"+typeof o+"'";
break;case "boolean":
ostr += (o)?"true":"false";
break;case "number":
ostr += o;
break;case "string":
ostr += "'"+o+"'";
break;case "object":
if(o == null){
ostr += "null";
}else if(o instanceof Array){
ostr += "[";
for(var i=0,il=o.length;i<il;i++){
getO(o[i]);
ostr += ", ";
}
ostr=ostr.slice(0,-2)+"]";
}else{
ostr += "{";
for (var key in o){
ostr += "'"+key+"': ";
getO(o[key]);
ostr += ", ";
}
ostr=ostr.slice(0,-2)+"}";
}
break;
}
}
getO(o);
console.log(ostr);
}



If you are using another browser, you can just set it to alert, rather than console.log on the last line

0 Comments

Post New Comment
Add comments here
Name:
Email:
URL:
Comment:BoldItalicUnderlineCreate linkCode BlockInsert Unordered List

JQuery/PHP Website and Applications Developer, based in Ireland.
Interests: Open Source Software, Supercomputers, Financial Markets, Sport, Science, Sustainable Energy. AGW Skeptic.

follow paulhan on twitter
Help me build a supercomputer