views:

6464

answers:

5

Hi All,

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!

+7  A: 

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

I was able to find this jQuery extension though.

Paolo Bergantino
This is perfect. I've been using console.log, but didn't realize I could pass it an object. Durr...
Eli
+3  A: 

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?

CMS
+1  A: 

You can also do

console.log("a = %o, b = %o", a, b);

where a and b are objects.

Bill Zeller
+1  A: 

Top comment has a broken link to the console.log documentation for Firebug, so here is a link to the wiki article about Console. I started using it and am quite satisfied with it as an alternative to PHP's print_r().

Also of note is that Firebug gives you access to returned JSON objects even without you manually logging them:

  • In the console you can see the url of the AJAX response.
  • Click the triangle to expand the response and see details.
  • Click the JSON tab in the details.
  • You will see the response data organized with expansion triangles.

This method take a couple more clicks to get at the data but doesn't require any additions in your actual javascript and doesn't shift your focus in Firebug out of the console (using console.log creates a link to the DOM section of firebug, forcing you to click back to console after).

For my money I'd rather click a couple more times when I want to inspect rather than mess around with the log, especially since keeps the console neat by not adding any additional cruft.

jeremyclarke