tags:

views:

1094

answers:

5

I am using jQuery. I am dealing with JSON object and time and again I need to look at the data. I do alert(data) and I get nothing useful.

In the Prototype world they have inspect method which is highly useful. inspect method in Prototype

I am looking for equivalent method in jQuery. I looked at the API and couldn't find anything. I am sure someone would have developed some plugin to solve this problem.

+3  A: 

You can use the jQuery.param function, which will format it into a querystring format.

alert(jQuery.param({ width:1680, height:1050 }));
// shows "width=1680&height=1050"
bdukes
Awesome. It works!
Neeraj Singh
Neeraj Singh
A: 

You can do this, too...

$.getJSON("some/url/here", { /* optional params */ }, function(json) {
    alert("get returned: " + json.toString());
});
Jarrett Meyer
Calling .toString() on a plain JavaScript object just shows "[object Object]," nothing helpful.
bdukes
Ditto. Calling toString() does not help.
Neeraj Singh
+6  A: 

If you are using FireBug, you can just call console.log(myJsonObject), and FireBug will give you a nice display of your JSON object in the console.

bdukes
I will go as far to say that this is the best way to do it because you absolutely SHOULD be using firebug :P
micmcg
+1  A: 

Also, firefox and other good browsers support toSource() method on objects and functions.

alert(foo.toSource())

alamar
+3  A: 

I have the best result with http://www.JSON.org/json2.js. As the docs say:

    JSON.stringify(value, replacer, space)
        value       any JavaScript value, usually an object or array.

        replacer    an optional parameter that determines how object
                    values are stringified for objects. It can be a
                    function or an array of strings.

        space       an optional parameter that specifies the indentation
                    of nested structures. If it is omitted, the text will
                    be packed without extra whitespace. If it is a number,
                    it will specify the number of spaces to indent at each
                    level. If it is a string (such as '\t' or ' '),
                    it contains the characters used to indent at each level.

Just include the library and call alert(JSON.stringify(data)) to see a legible representation of your object.

edavey