477

Typically if we just use alert(object); it will show as [object Object]. How to print all the content parameters of an object in JavaScript?

0

15 Answers 15

805

This will give you very nice output with an indented JSON object using JSON.stringify:

alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));

The second argument (replacer) alters the contents of the string before returning it.

The third argument (space) specifies how many spaces to use as white space for readability.

JSON.stringify documentation here.

Sign up to request clarification or add additional context in comments.

6 Comments

+1 for cross-platform support. Standardized in ECMAScript 5th Edition, with support in Firefox 3.6, Chrome (ver?), Safari 4, and IE8. FYI: The 4 parameter is the number of spaces for each indention level. It may also be a string, e.g. "\t". The null parameter is a placeholder for a filtering function, if you want to limit what gets shown. See: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
endlessly useful in the IE8 JS debugger.
This doesn't work for objects with circular reference chains - Chrome gives an error: TypeError: Converting curcular structure to JSON
I'm seeing this same circular structure error in Chrome: Uncaught TypeError: Converting circular structure to JSON. Am I doing something wrong, or is this endemic to Chrome?
Nice answer. You saved my day, I'm using this in Phonegap.
|
330

If you are using Firefox, alert(object.toSource()) should suffice for simple debugging purposes.

7 Comments

Also supported in IE9 (if not earlier), but not by Chrome 17 or Safari 5.
Is there a cross-browser way of doing something similar?
In recent browsers, you can use console.dir(object) to dump the contents of an object to the debugging console (F12 on most browsers).
I was trying to use this in console.log(object.toSource()); didn't work for me..
@BinitaBharati well, I answered this in 2009 when console.dir did not exist ... maybe in 2037, console.dir would no longer be the best ..
|
78

Aside from using a debugger, you can also access all elements of an object using a foreach loop. The following printObject function should alert() your object showing all properties and respective values.

function printObject(o) {
  var out = '';
  for (var p in o) {
    out += p + ': ' + o[p] + '\n';
  }
  alert(out);
}

// now test it:
var myObject = {'something': 1, 'other thing': 2};
printObject(myObject);

Using a DOM inspection tool is preferable because it allows you to dig under the properties that are objects themselves. Firefox has FireBug but all other major browsers (IE, Chrome, Safari) also have debugging tools built-in that you should check.

2 Comments

Might want to add if (o.hasOwnProperty(p)) inside the loop
That's a good idea, but when debugging I'd rather see it all. Perhaps even better would be something like: for (var p in o) { if (!o.hasOwnProperty(p)) out += '(inherited) '; out += p + ': ' + o[p] + '\n'; }
33

If you just want to have a string representation of an object, you could use the JSON.stringify function, using a JSON library.

1 Comment

this is the best answer IMHO, it works across browsers
17

You could Node's util.inspect(object) to print out object's structure.

It is especially helpful when your object has circular dependencies e.g.

$ node

var obj = {
   "name" : "John",
   "surname" : "Doe"
}
obj.self_ref = obj;

util = require("util");

var obj_str = util.inspect(obj);
console.log(obj_str);
// prints { name: 'John', surname: 'Doe', self_ref: [Circular] }

It that case JSON.stringify throws exception: TypeError: Converting circular structure to JSON

1 Comment

Thank. This can be used in places where printing goes to the logs.
14

Print content of object you can use

console.log(obj_str);

you can see the result in console like below.

Object {description: "test"} 

For open console press F12 in chrome browser, you will found console tab in debug mode.

Comments

8

You should consider using FireBug for JavaScript debugging. It will let you interactively inspect all of your variables, and even step through functions.

Comments

7

Use dir(object). Or you can always download Firebug for Firefox (really helpful).

3 Comments

dir? need include any special js file?
its only needs the firebug extension
console.dir(object) Prints output in Firebug's Console pane. Returns "_firebugIgnore", so it's not for use with alert(). Documented at getfirebug.com/wiki/index.php/…
3

Javascript for all!

String.prototype.repeat = function(num) {
    if (num < 0) {
        return '';
    } else {
        return new Array(num + 1).join(this);
    }
};

function is_defined(x) {
    return typeof x !== 'undefined';
}

function is_object(x) {
    return Object.prototype.toString.call(x) === "[object Object]";
}

function is_array(x) {
    return Object.prototype.toString.call(x) === "[object Array]";
}

/**
 * Main.
 */
function xlog(v, label) {
    var tab = 0;

    var rt = function() {
        return '    '.repeat(tab);
    };

    // Log Fn
    var lg = function(x) {
        // Limit
        if (tab > 10) return '[...]';
        var r = '';
        if (!is_defined(x)) {
            r = '[VAR: UNDEFINED]';
        } else if (x === '') {
            r = '[VAR: EMPTY STRING]';
        } else if (is_array(x)) {
            r = '[\n';
            tab++;
            for (var k in x) {
                r += rt() + k + ' : ' + lg(x[k]) + ',\n';
            }
            tab--;
            r += rt() + ']';
        } else if (is_object(x)) {
            r = '{\n';
            tab++;
            for (var k in x) {
                r += rt() + k + ' : ' + lg(x[k]) + ',\n';
            }
            tab--;
            r += rt() + '}';
        } else {
            r = x;
        }
        return r;
    };

    // Space
    document.write('\n\n');

    // Log
    document.write('< ' + (is_defined(label) ? (label + ' ') : '') + Object.prototype.toString.call(v) + ' >\n' + lg(v));
};



// Demo //

var o = {
    'aaa' : 123,
    'bbb' : 'zzzz',
    'o' : {
        'obj1' : 'val1',
        'obj2' : 'val2',
        'obj3' : [1, 3, 5, 6],
        'obj4' : {
            'a' : 'aaaa',
            'b' : null
        }
    },
    'a' : [ 'asd', 123, false, true ],
    'func' : function() {
        alert('test');
    },
    'fff' : false,
    't' : true,
    'nnn' : null
};

xlog(o, 'Object'); // With label
xlog(o); // Without label

xlog(['asd', 'bbb', 123, true], 'ARRAY Title!');

var no_definido;
xlog(no_definido, 'Undefined!');

xlog(true);

xlog('', 'Empty String');

Comments

2

You can give your objects their own toString methods in their prototypes.

Comments

2

You can use json.js from http://www.json.org/js.html to change json data to string data.

Comments

2

You can also use Prototype's Object.inspect() method, which "Returns the debug-oriented string representation of the object".

http://api.prototypejs.org/language/Object/inspect/

1 Comment

Its quite unhelpful for a javascript library to call itself after a fundamental aspect of a language.
2

Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.

Function

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

Usage

var data = [1, 2, 3, 4];
print_r(data);

Comments

0

Internet Explorer 8 has developer tools which is similar to Firebug for Firefox. Opera has Opera DragonFly, and Google Chrome also has something called Developer Tools (Shift+Ctrl+J).

Here is more a more detailed answer to debug JavaScript in IE6-8: Using the IE8 'Developer Tools' to debug earlier IE versions

Comments

-6

I faced similar problem, The reason for it was i make use of ajax to fetch data. In this case i had made two asynchronous ajax call. In one i just return string msg and show in alert. In second ajax call i fetch arraylist in json format and decode it in js. So my second request use to process first and i was getting alert of object.

So just check. 1. alert should contain string. 2. If u get arrayList or any other Object decode it.

All the best!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.