269

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?

1
  • 6
    as a sidenote, for (property in obj) will list all properties, even the inherited ones. So you will get a lot of extraneous one cominng for Object.prototype and any 'mother class'. This is unconvenient with json objects. You have to filter them with hasOwnProperty() to get only the properties that this object owns. Commented Feb 8, 2011 at 12:55

13 Answers 13

682

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.

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

5 Comments

I'm surprised this answer is at the bottom...... This should be the accepted answer :-)
What if you don't want a string representation, but rather the object as it would appear in a code editor?
@SuperUberDuper: ...Then you wouldn't be trying to build a string representation, now, would you. :)
I believe SuperUberDuper was asking if the object could be logged or viewed without converting it to a string. If viewing in the browser the DOM needs an element, you can stringify json so and set an elements contents innerHTML to that string to view it on the page.
For example: import Json from './data.json'; var el = document.createElement('div'); el.innerHTML = JSON.stringify(Json);
147

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.

9 Comments

It's worth mentioning that in chrome (and perhaps other browsers) when combined with a string like this: console.log("object: " + obj) it does not display the object, but instead will output "object: [Object obj]".
@Shahar console.log("object: %O", obj) (Chrome) or console.log("object: %o", obj) (Firefox|Safari) will give you access to the object details, see my answer below.
@DaveAnderson good shot for the object formatting in the console.
In addition to @DaveAnderson 's method, using a comma to separate strings from objects can also work: console.log("My object: ", obj)
@EzekielVictor Yes, that's the point ^^ That way you know what variable is output in the log. With one it's not that useful, but when having multiple you can just do console.log({i, array, element}) and get a complete picture without having to add text to it that describes what it is. Of course only works with well named variables.
|
69

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.

Comments

56

try console.dir() instead of console.log()

console.dir(obj);

MDN says console.dir() is supported by:

  • FF8+
  • IE9+
  • Opera
  • Chrome
  • Safari

4 Comments

Only available in IE9+
console.dir() is also available in FF8+, Opera, Chrome and Safari: developer.mozilla.org/en-US/docs/Web/API/console.dir
what about node js ?
good , but does not support string concatenation like log("string " + variable)
47

to Print JSON parsed object just type

console.log( JSON.stringify(data, null, " ") );

and you will get output very clear

Comments

31

Use string formats;

console.log("%s %O", "My Object", obj);

Chrome has Format Specifiers with the following;

  • %s Formats the value as a string.
  • %d or %i Formats the value as an integer.
  • %f Formats the value as a floating point value.
  • %o Formats the value as an expandable DOM element (as in the Elements panel).
  • %O Formats the value as an expandable JavaScript object.
  • %c Formats the output string according to CSS styles you provide.

Firefox also has String Substitions which have similar options.

  • %o Outputs a hyperlink to a JavaScript object. Clicking the link opens an inspector.
  • %d or %i Outputs an integer. Formatting is not yet supported.
  • %s Outputs a string.
  • %f Outputs a floating-point value. Formatting is not yet supported.

Safari has printf style formatters

  • %d or %i Integer
  • %[0.N]f Floating-point value with N digits of precision
  • %o Object
  • %s String

3 Comments

nice reference answer
%O is really helpful
FYI, in Firefox, %O now seems to output as an expandable object inside the console.
6

Nice and simple:

console.log("object: %O", obj)

4 Comments

could you please describe what does %O for? should it be O specifically? - your solution work like a charm
O stands for object, so as long as the object can be printing as a string, it should be printed with no issues. This has helped me troubleshoot in many cases where I wasn't sure where the error is
I forgot to inform here, actually we don't need to use %O. We can directly use console.log("object: ", obj) thank you @mbenhalima
So then this is the same as the accepted answer.
3

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

Comments

3

If you want to debug why not use console debug

window.console.debug(jsonObject);

Comments

3

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.

Comments

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

2

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));

Comments

1

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

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.