I've got a javascript object which has been JSON parsed using JSON.parse I now want to print the object so I can debug it (something is going wrong with the function). When I do the following...
for (property in obj) {
output += property + ': ' + obj[property]+'; ';
}
console.log(output);
I get multiple [object Object]'s listed. I'm wondering how would I print this in order to view the contents?
13 Answers
You know what JSON stands for? JavaScript Object Notation. It makes a pretty good format for objects.
JSON.stringify(obj) will give you back a string representation of the object.
Most debugger consoles support displaying objects directly. Just use
console.log(obj);
Depending on your debugger this most likely will display the object in the console as a collapsed tree. You can open the tree and inspect the object.
If you want a pretty, multiline JSON with indentation then you can use JSON.stringify with its 3rd argument:
JSON.stringify(value[, replacer[, space]])
For example:
var obj = {a:1,b:2,c:{d:3, e:4}};
JSON.stringify(obj, null, " ");
or
JSON.stringify(obj, null, 4);
will give you following result:
"{
"a": 1,
"b": 2,
"c": {
"d": 3,
"e": 4
}
}"
In a browser console.log(obj) does even better job, but in a shell console (node.js) it doesn't.
try console.dir() instead of console.log()
console.dir(obj);
MDN says console.dir() is supported by:
- FF8+
- IE9+
- Opera
- Chrome
- Safari
to Print JSON parsed object just type
console.log( JSON.stringify(data, null, " ") );
and you will get output very clear
Use string formats;
console.log("%s %O", "My Object", obj);
Chrome has Format Specifiers with the following;
%sFormats the value as a string.%dor%iFormats the value as an integer.%fFormats the value as a floating point value.%oFormats the value as an expandable DOM element (as in the Elements panel).%OFormats the value as an expandable JavaScript object.%cFormats the output string according to CSS styles you provide.
Firefox also has String Substitions which have similar options.
%oOutputs a hyperlink to a JavaScript object. Clicking the link opens an inspector.%dor%iOutputs an integer. Formatting is not yet supported.%sOutputs a string.%fOutputs a floating-point value. Formatting is not yet supported.
Safari has printf style formatters
%dor%iInteger%[0.N]fFloating-point value with N digits of precision%oObject%sString
Nice and simple:
console.log("object: %O", obj)
Just use
console.info("CONSOLE LOG : ")
console.log(response);
console.info("CONSOLE DIR : ")
console.dir(response);
and you will get this in chrome console :
CONSOLE LOG :
facebookSDK_JS.html:56 Object {name: "Diego Matos", id: "10155988777540434"}
facebookSDK_JS.html:57 CONSOLE DIR :
facebookSDK_JS.html:58 Objectid: "10155988777540434"name: "Diego Matos"__proto__: Object
If you want to debug why not use console debug
window.console.debug(jsonObject);
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);
The following code will display complete json data in alert box
var data= '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
json = JSON.parse(data);
window.alert(JSON.stringify(json));
If you're working in js on a server, just a little more gymnastics goes a long way... Here's my ppos (pretty-print-on-server):
ppos = (object, space = 2) => JSON.stringify(object, null, space).split('\n').forEach(s => console.log(s));
which does a bang-up job of creating something I can actually read when I'm writing server code.
I don't know how it was never made officially, but I've added my own json method to console object for easier printing stringified logs:
Observing Objects (non-primitives) in javascript is a bit like quantum mechanics..what you "measure" might not be the real state, which already have changed.
console.json = console.json || function(argument){
for(var arg=0; arg < arguments.length; ++arg)
console.log( JSON.stringify(arguments[arg], null, 4) )
}
// use example
console.json( [1,'a', null, {a:1}], {a:[1,2]} )
Many times it is needed to view a stringified version of an Object because printing it as-is (raw Object) will print a "live" version of the object which gets mutated as the program progresses, and will not mirror the state of the object at the logged point-of-time, for example:
var foo = {a:1, b:[1,2,3]}
// lets peek under the hood
console.log(foo)
// program keeps doing things which affect the observed object
foo.a = 2
foo.b = null