Site Moved

This site has been moved to a new location - Bin-Blog. All new post will appear at the new location.

Bin-Blog

Dump() Function - Javascript equivalent of PHP's print_r()

The moment I saw the print_r() function of PHP, I fell in love with it. It is a very necessary function and I cant understand why no other language supports it. Perl does - if you are using the Data::Dumper module. I have created a function in PHP that will call print_r() function. It will put the code generated by the print_r function inside <pre> tags. That will make the data readable from the browser.

Latest Version of Dump() Function - Javascript equivalent of PHP's print_r() available at OpenJS

/** Function : dump()
* Arguments  : $data - the variable that must be displayed
***********************************************************************************
* Version    : 1.01.B
* Author     : Binny V A(binnyva (at) hotmail (dot) com : http://www.geocities.com/binnyva)
* Date       : June 3, 2005
* Last Update: Wednesday, July 13 2005
* Prints a array, an object or a scalar variable in an easy to view format.
***********************************************************************************/
function dump($data) {
if(is_array($data)) { //If the given variable is an array, print using the print_r function.
 print "<pre>-----------------------\n";
 print_r($data);
 print "-----------------------</pre>";
} elseif (is_object($data)) {
 print "<pre>==========================\n";
 var_dump($data);
 print "===========================</pre>";
}
else {
 print "=========&gt; ";
 var_dump($data);
 print " <=========";
}
}
I have ported the print_r function to javascript - hope that you will find this useful.
/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];
 
  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
} 
This is how the function is called. In this example we will give a complex array as the argument.
//Calling the function...
function init() {
var arra = new Array("Hloo",'s',23,23.1,"Hello World");
var assoc = {
 "val"  : "New",
 "number" : 14,
 "theting" : arra
};

alert(dump(assoc));
}
window.onload=init;
The result will be shown in the following format.
'val' => "New"
'number' => "14"
'theting' ...
   '0' => "Hloo"
   '1' => "s"
   '2' => "23"
   '3' => "23.1"
   '4' => "Hello World"
Technorati Tags:
Del.icio.us Tags :

30 Comments:

Anonymous said...

Thanks for the JavaScript function - this just saved me about a half an hour of wasted effort trying to find a bug in my code (it was in a rather obscure place).

Anonymous said...

Excellent function!

BTW, it's easier to set up a textarea at end of html page and dump into that textarea instead of dumping to alert boxes, which is too small.

Anonymous said...

Thanks Binny! This was just what I was looking for -- saved me from having to write it myself.

Anonymous said...

YOu are my Hero!!!!

Anonymous said...

I absolutely love you! You've saved me so much time!!!!!!!

Although I'm lazy so I added the alert directly to the function :P

Good idea about the text areas anonymous. Another idea would to have another tab open and write the data to that.

/me adds to dump function

Anonymous said...

One issue. It can cause an error of "too much recursion" if you use forms with radio boxes.

Anonymous said...

great work, thx

Unknown said...

Thank you very much!

I modified your function a little because I work with arrays created from RegExp and I wanted to avoid annoying 'index' and 'input' values repeated many times:


function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var i=0;i<arr.length;i++) {
var value = arr[i];

if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + i + "' ==> ";
dumped_text += "{\n" + dump(value,level+1) + level_padding + "}\n";
} else {
dumped_text += level_padding + "'" + i + "' ==> \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")\n";
}
return dumped_text;
}

Binny V A said...

Thanks everybody.

eteran said...

Thank you, that function helped me alot!

Anonymous said...

Awesome function, exactly what I've been needing for ages, only I'm far too lazy to try and get my head around writing it.

you're a bloody star :)

Anonymous said...

THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU! THANK YOU!

oh, and...um... THANK YOU!

Anonymous said...

//dumped_text += dump(value,level+1);

this line seems to cause errors if used on a page that's using Prototype js.


[Exception... "'Permission denied to create wrapper for object of class UnnamedClass' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x8057001e (NS_ERROR_XPC_JS_THREW_STRING)" location: "<unknown>" data: no]

Anonymous said...

Cool, just what I was looking for !!

Anonymous said...

Thanks!

Anonymous said...

THANKS SO MUCH!

Anonymous said...

this is a great script. thank you for your work. helpfull for me.

Anonymous said...

one more THANKS doesn't hurt !!!

Anonymous said...

Thanks a bunch. This function works very good.

Anonymous said...

Thank you for the JS print_r!

jason said...

Great - thank you!

Chee Tji Hun said...

cool was about to write one myself love the recursion, love the fact that it returns the type format if it is anything other than object.

Anonymous said...

Thank you so much.........

Anonymous said...

Excelent!!!

Unknown said...

many thanks for the javascript function!!!

Anonymous said...

Thanks a lot!

I'm new to javascript, and was looking for a way to recursively dump the contents of a variable. Just like you, I was used to doing this in PHP, so I was also surprised to see that Javascript does not have that functionality. Luckily I stumbled onto your blog while looking for this elusive function!

Clifford James said...

This function here is a exact copy of php's print_r function only then in JavaScript! Go check it out!

Greg said...

Hey! It was so useful to visualize the response of Google API geocoder.getLocations(GLatLng)!
In 2 minutes I go my answer!
Thank you :)

Usher web said...

Ey man!!! thanks! i needed a function like var_export() in PHP, but in javascript. And your function is simple and power.

I wants to share with others my improvement in the "visual look" of the output ;)


function js_var_export(arr,level) {
var dumped_text = '';
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = '';
for(var j=0;j<level+1;j++) level_padding += ' ... ';

if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += '<br />' + level_padding + '\'' + item + '\' ...';
dumped_text += js_var_export(value,level+1);
} else {
dumped_text += '<br />' + level_padding + '\'' + item + '\' =\> \'' + value + '\'';
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = '===& gt;'+arr+'& lt;===('+typeof(arr)+')';
}
return dumped_text;
}

Anonymous said...

I've made the function compatible with circular structures. Just added a maxLevel argument:

function dump(arr,maxLevel,level) {
var dumped_text = "";
if(!level) level = 0;
if(!maxLevel) maxLevel = 5;
if(level >= maxLevel) return;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}

cheers!