259

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?

oHo
  • 51,447
  • 27
  • 165
  • 200
Skizit
  • 43,506
  • 91
  • 209
  • 269
  • 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. – BiAiB Feb 08 '11 at 12:55

13 Answers13

669

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.

cHao
  • 84,970
  • 20
  • 145
  • 172
  • 13
    I'm surprised this answer is at the bottom...... This should be the accepted answer :-) – Mingyu Sep 21 '15 at 07:53
  • 1
    What if you don't want a string representation, but rather the object as it would appear in a code editor? – SuperUberDuper Dec 08 '15 at 09:20
  • 6
    @SuperUberDuper: ...Then you wouldn't be trying to build a string representation, now, would you. :) – cHao Dec 08 '15 at 15:42
  • 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. – jasonleonhard Dec 19 '17 at 01:47
  • For example: import Json from './data.json'; var el = document.createElement('div'); el.innerHTML = JSON.stringify(Json); – jasonleonhard Dec 19 '17 at 01:47
148

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.

RoToRa
  • 37,635
  • 12
  • 69
  • 105
  • 150
    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 Jan 22 '15 at 02:13
  • 33
    @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. – Dave Anderson Nov 18 '15 at 20:19
  • 1
    @DaveAnderson good shot for the object formatting in the console. – lekant Oct 11 '16 at 03:20
  • @Shahar thanks, yours was the information I needed. Should be added to the answer. – Leo Flaherty Jul 28 '17 at 10:36
  • 5
    In addition to @DaveAnderson 's method, using a comma to separate strings from objects can also work: `console.log("My object: ", obj)` – Shahar Mar 20 '18 at 07:57
  • The better solution to the here mentioned methods is simply `console.log({obj})`. (better as in better readable output and less to write, but still clear syntax) – SourceOverflow May 01 '18 at 14:05
  • @Shahar Exactly. thats why I've reached in this page. – Adil Saju Feb 28 '19 at 06:09
  • @SourceOverflow, not exactly. You wrapped `obj` in extraneous `{...}` braces which serves to create a harmless, but somewhat annoying, layer of indirection. `{foo}` is ECMA shorthand for _an object literal with a key `foo` whose value is the scoped variable `foo`_, i.e. producing the same thing as `{foo: foo}`. The actual best solution is `console.log(obj)`, or `console.log('My text:', obj)` (note the auto-concatenation that happens without need for string format specs). Of course, if you're already in the console REPL, just type `obj` then ENTER ↩—no `console.log` boilerplate necessary… – Ezekiel Victor Jun 01 '23 at 15:07
  • @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. – SourceOverflow Jul 02 '23 at 18:56
66

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.

David
  • 3,166
  • 2
  • 30
  • 51
Lukasz Wiktor
  • 19,644
  • 5
  • 69
  • 82
56

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

console.dir(obj);

MDN says console.dir() is supported by:

  • FF8+
  • IE9+
  • Opera
  • Chrome
  • Safari
oHo
  • 51,447
  • 27
  • 165
  • 200
Distdev
  • 2,312
  • 16
  • 23
47

to Print JSON parsed object just type

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

and you will get output very clear

BERGUIGA Mohamed Amine
  • 6,094
  • 3
  • 40
  • 38
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
Dave Anderson
  • 11,836
  • 3
  • 58
  • 79
4

Nice and simple:

console.log("object: %O", obj)
Pang
  • 9,564
  • 146
  • 81
  • 122
mbenhalima
  • 722
  • 1
  • 9
  • 20
  • 1
    could you please describe what does %O for? should it be O specifically? - your solution work like a charm – Anthonius Jun 10 '20 at 17:02
  • 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 – mbenhalima Jun 12 '20 at 00:15
  • I forgot to inform here, actually we don't need to use %O. We can directly use console.log("object: ", obj) thank you @mbenhalima – Anthonius Jun 25 '20 at 19:12
  • So then this is the same as the accepted answer. – Kalnode Jan 06 '21 at 16:06
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
diego matos - keke
  • 2,099
  • 1
  • 20
  • 11
3

If you want to debug why not use console debug

window.console.debug(jsonObject);
Ruwantha
  • 2,603
  • 5
  • 30
  • 44
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);
Rayiez
  • 1,420
  • 19
  • 20
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));
Kiran Kumar Kotari
  • 1,078
  • 1
  • 10
  • 24
2

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.

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
vsync
  • 118,978
  • 58
  • 307
  • 400