Print content of JavaScript object? [duplicate]
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?
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.
If you are using Firefox, alert(object.toSource())
should suffice for simple debugging purposes.
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.
If you just want to have a string representation of an object, you could use the JSON.stringify
function, using a JSON library.
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