jQuery: print_r() display equivalent?

05/07/2020 03:00:02

Possible Duplicate:
JavaScript data formatting/pretty printer

I am getting a bit tired of looking at unformatted json blobs in FireBug.

Does anyone know an equivalent to PHP's print_r() for jQuery?

Something that would recursively make a display string from an object or array, that I could display on the page for quick debugging?

Thanks!

Verified Answer (69 Votes)

01/19/2009 11:00:43

console.log is what I most often use when debugging.

I was able to find this jQuery extension though.

69

Answer #2 (44 Votes)

01/19/2009 11:11:39

You could use very easily reflection to list all properties, methods and values.

For Gecko based browsers you can use the .toSource() method:

var data = new Object();
data["firstname"] = "John";
data["lastname"] = "Smith";
data["age"] = 21;

alert(data.toSource()); //Will return "({firstname:"John", lastname:"Smith", age:21})"

But since you use Firebug, why not just use console.log?

44

Answer #3 (16 Votes)

11/01/2011 19:05:52

How about something like:

<script src='http://code.jquery.com/jquery-latest.js'></script>

function print_r(o){
return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;'); }
16
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.