2044

How do I display the content of a JavaScript object in a string format like when we alert a variable?

The same formatted way I want to display an object.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
maxjackie
  • 22,386
  • 6
  • 29
  • 37
  • 7
    Would you please reword your question? What do you mean by "formatted way"? As in, with rich formatting, like bold/italic/etc? – Sasha Chedygov Jun 05 '09 at 19:03
  • is there a way to display the runtime value of a variable by printing the value of the variable using some console commands? – BlackPanther Aug 03 '15 at 06:54
  • 1
    @BlackPanther Just do `console.log("", yourObject1, yourObject2, yourObject3, etc...);`. A shorter version is to just do `console.log(yourObject1, yourObject2, etc...);`. – tom_mai78101 Jul 31 '17 at 11:52
  • Like this `console.log('a string', aNumber, anObject)` – onmyway133 Oct 15 '18 at 11:58
  • 1
    Some tips: You can use colors to have a better view of: console.log('%c Sample Text', 'color:green;'); Or add some VAR in the text using: console.log(\`Sample ${variable}\`, 'color:green;'); – Gilberto B. Terra Jr. Jan 29 '19 at 11:34
  • My problem was corrupted object which is ngModel of a select box and the [value] was used for option, instead of [ngValue]. When ngValue is used, the console.log is fine. – Dat TT Feb 26 '19 at 02:06
  • hey, i know this is very necromantic, but can you change the selected answer, ive added a lot of extra ways, not just one to display the object, and it will give me a chance to gain fame :D – Max Alexander Hanna Sep 25 '19 at 12:55
  • This helped me a lot - https://code-maven.com/logging-javascript-objects – Betlista Jan 07 '20 at 12:38
  • This may help [How can I serialize an input File object to JSON?](https://stackoverflow.com/q/24139216/9935654) – Carson Sep 20 '21 at 19:56

40 Answers40

2402

Use native JSON.stringify method. Works with nested objects and all major browsers support this method.

str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()

Link to Mozilla API Reference and other examples.

obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)

Use a custom JSON.stringify replacer if you encounter this Javascript error

"Uncaught TypeError: Converting circular structure to JSON"
user229044
  • 232,980
  • 40
  • 330
  • 338
Sandeep
  • 28,307
  • 3
  • 32
  • 24
  • JSON.stringify(obj) will not show all properties for array objects. eg `array = ["a","b"]; array["c"] = "c"`. When we do `JSON.stringify(array)` output is **"[ "a", "b" ]"** and when we do console.log(array) output is **["a", "b", c: "c"]** – airboss May 10 '13 at 20:31
  • I use JSON.stringify with [toastr](https://github.com/CodeSeven/toastr) to output for debugging. [Live Example](http://jsfiddle.net/absynce/ACGRx/) – absynce May 17 '13 at 19:02
  • 3
    JSON.stringify can only show a small subset of javascript values, and will throw an exception for the rest - console.log does not have this problem. – Remember Monica Oct 01 '13 at 13:46
  • 11
    If you are a newbie like me, don't forget ```console.log``` i.e. ```console.log(JSON.stringify(obj,null, 4));``` – nilesh Dec 30 '13 at 03:49
  • 2
    "Uncaught TypeError: Converting circular structure to JSON" when ob=window. – Michael Jan 13 '14 at 23:04
  • Great for doing it without requiring a browser plugin. It is working for me, at least in simple and most common cases! – Marco Marsala Jan 23 '14 at 12:24
  • @Stefano If you wanna see the output without console, you can combine both options. JSON will put data into a string, then alert() it: `alert(JSON.stringify(object))` – m3nda Jan 24 '15 at 05:55
  • 5
    I had cases where it did not work : it showed `{}` for a non-empty object. So be sure to check with `console.log(obj)` before thinking your object is empty when `strigify()` returns `{}`. – Sindarus Aug 09 '16 at 14:31
  • stringify won't work if it's a DOM object. Solution is to simply split into 2 separate commands believe it or not: console.log("id:"); console.log(obj); – Collin Chaffin Mar 28 '17 at 21:55
  • 3
    > In Node.js, you can use [util.inspect(object)](http://nodejs.org/api/util.html#util_util_inspect_object_options). It automatically replaces circular links with "[Circular]". ----- credit: [Erel Segal-Halevi](https://stackoverflow.com/a/18354289/8015265) in that JSON.stringify replacer link – DaveLak Dec 19 '17 at 05:16
  • Notice that this, for example, is a valid javascript object: `{name: "John"}` but not valid JSON, so this method won't work in some cases. – Fernando Feb 04 '19 at 09:49
  • I was having to log my object to Google Analytics so I used `JSON.stringify(obj).toString()` – TimSmith-Aardwolf Jan 27 '20 at 16:07
  • For anyone else trying to actually raw print a prettified object on the page itself, all you need to do is wrap the object in a
     HTML tag. For benefiting from the improved indenting of this stringified JSON, wrap that string instead.
    – Koolstr Oct 15 '20 at 14:20
  • This answer works most of the time, but I had a circular reference error, this other answer helped me with that: [How can I print a circular structure in a JSON-like format?](https://stackoverflow.com/a/18354289/3154857) – Gilberto Treviño Apr 27 '22 at 19:54
1331

If you want to print the object for debugging purposes, use the code:

var obj = {
  prop1: 'prop1Value',
  prop2: 'prop2Value',
  child: {
    childProp1: 'childProp1Value',
  },
}
console.log(obj)

will display:

screenshot console chrome

Note: you must only log the object. For example, this won't work:

console.log('My object : ' + obj)

Note ': You can also use a comma in the log method, then the first line of the output will be the string and after that, the object will be rendered:

console.log('My object: ', obj);
Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Kenan Banks
  • 207,056
  • 34
  • 155
  • 173
  • 44
    That function also works on Google Chrome when using the JavaScript Console (Shift+Control+J or Shift+Control+I, depending on the Chrome version). Also note that `console.log(obj1, obj2)` works very nicely, too, so you don't have to call `console.log()` for every object when logging multiple variables. Also, always remember to remove all such calls in production, as it will break browsers that do not implement it (such as Internet Explorer). – Felix Apr 22 '10 at 09:31
  • 104
    Yes it prints [object Object] but it has a little expando-toggly button beside it that lets you inspect the contents of the object. – hughes Jul 05 '11 at 13:46
  • 12
    @hughes it actually can do both. i have an object i created with: var obj = { "foo" : false }; and another object that is being passed into a callback from a server, the one passed through the callback prints with the little arrow so you can open it up, the statically created one just prints [object Object] with no arrow. I'm trying to figure this out too, any other thoughts? – benstraw Jul 08 '11 at 00:08
  • 1
    Yes it print object but in Chrome console you could extend the arrow and take a look at the data, here's an image of how it look: http://i.imgur.com/goRDM.png – Jimmy Sep 07 '11 at 16:09
  • 4
    @Felix: Great point about breaking browsers such as IE. You can also use `if(console && console.log) { console.log(obj1, obj2); }` without worrying about breaking browsers that don't support console.log. – chocojosh Nov 22 '11 at 21:52
  • 4
    if you don't have the expand-button maybe you tried to be a smartass like me and called `toString()` on the object hoping for enlightenment. However this kinda forces the [object Object] output. Keep that in mind to save some of your life time :) – nuala Apr 10 '12 at 09:55
  • Just to note: This is not the answer if you are trying to develop an HTA on Microsoft Windows. This is because HTA's run in elevated privileges and don't get a console or other UI components. – Julian Knight Jun 19 '12 at 20:17
  • 1
    IE does support `console.log` if you have the console open. However, it doesn't give you a nice clickable object you can expand. – Ruan Mendes Aug 08 '12 at 23:48
  • You need to have the IE Developer tools debugger running which creates the console.log thingy for you. – GuruM Sep 21 '12 at 07:59
  • If the, obvious, `console.log` is not working in your environment. (E.g. eclipse and xCode have not such a smooth console as FF or Chrome) consider Flavius answer: http://stackoverflow.com/a/957652/1063730 Works nice in more rough coding-eco-systems :) – nuala Dec 06 '12 at 13:29
  • 1
    @chocojosh, `console && console.log && console.log(obj1, obj2);` as an expression can also do :) – Om Shankar Jan 03 '13 at 16:57
  • 130
    `console.log("id:"+obj);` won't output correctly as it outputs a string as you see it there, you need to specify it like this: `console.log("id:"); console.log(obj);` – Anriëtte Myburgh Mar 05 '13 at 11:06
  • 2
    `console.log('%c red text, %c green bg', 'color: red', 'background: green' );` `%c` can be used to style console.log's with colors. it's helpful if you have too many and need to find one easy and modules that console log often – dansch Sep 16 '13 at 16:54
  • 1
    You can also see properties of an object by loop. Like for(var key in obj) { var value = obj[key]; console.log(key + " - " + value); } – Riz Oct 04 '13 at 12:07
  • 1
    -1 Not cross-platform (see any mobile browser, where to get a console you have to have a *remote machine* available for debugging) – Michael Jan 13 '14 at 23:04
  • For the benefit of future rookies, @AnriëtteMyburgh's answer `console.log("id:"); console.log(obj);` works in most modern browsers. So let's use that until we get good enough to need something different. – Joshua Dance Mar 13 '14 at 20:57
  • 3
    **Important** console.log prints actually a reference to the object so if the object fields change after the logging so does the output see [this](http://stackoverflow.com/questions/7389069/console-log-object-at-current-state) – kon psych May 27 '14 at 06:07
  • 2
    this is just NOT the right answer, console.dir(value) is, even if in most cases console.log(value) will result in the same thing (IF the value is an object) – Pizzaiola Gorgonzola Jun 03 '14 at 12:43
  • 1
    didnt see this mentioned but couldnt you just console.log("id:", obj); in every browser and node this results and printing the string and object without creating the '[object Object]' – Snymax Dec 05 '14 at 15:19
  • 20
    Try `console.log(JSON.stringify(obj))` or `console.dir(obj)` – Robot Boy Jun 03 '15 at 07:53
  • 1
    when I do console.log(myObject) I get [object Object] so how can your answer be the right one? If I can't just do a console.log on my object as you did and see the graph...? And if i try JSON.stringify, I get TypeError: Converting circular structure to JSON – PositiveGuy May 14 '16 at 22:15
  • 1
    @AnriëtteMyburgh you can also say console.log("id:", obj) – dz210 Jun 27 '16 at 14:46
  • Safari has a bunch of console commands that let you work with [object Object]. For instance try the "keys" or "values" commands. Yep, way better if this was just a drop down but you can't have everything. https://developer.apple.com/library/iad/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html – Raydot Aug 19 '16 at 21:39
  • 4
    WRONG. Like others have said, console.log actually prints a reference to the object at last executable state. It WILL CHANGE! This can cost you a lot of wasted time as you search for bugs that don't exist. Better to use JSON.stringify. – Steven2163712 May 15 '17 at 14:30
  • 1
    Unfortunately, all I see is the text "" (using modern Firefox). Works fine on old Firefox and Chrome. – HoldOffHunger Apr 03 '18 at 16:53
  • 1
    Does not work with Android WebView. It does have a console output which can be seen on a debugger, but it does not support string substitutions like %o at this time. Android WebView is how you embed a browser in an app. – John Moore Oct 10 '19 at 18:29
  • What if `console` is not available? Like in Nashorn I am using in Keycloak? – xbmono Aug 26 '21 at 05:24
  • Adding to @Steven2163712 's comment: this logs to the console a live reference to the object. If you want the contents of the object at the time of logging, some other solution is required. – studog Jul 06 '23 at 16:52
421
var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);
Ben McCann
  • 18,548
  • 25
  • 83
  • 101
Flavius Stef
  • 13,740
  • 2
  • 26
  • 22
  • 1
    This is what exactly i want. I am using google maps v3 and the directionrenderer returns an object. That has four items and in that one objects name keeps changing so we need to find that. For that this method really helped. Besides this way we can get all the names of the properties and objects. Or is there any other way to find the names of the objects and properties? – Jayapal Chandran Apr 28 '11 at 14:08
  • 3
    You probably want to mask out the built in cruft with hasOwnProperty most of the time. – John Apr 20 '12 at 00:58
  • 1
    A little late finding this, but as it got requested on my birthday last year (29th aug), here is a working fiddle. http://jsfiddle.net/MrMarlow/fq53o6o9/ – MrMarlow Sep 11 '15 at 11:06
  • This is an old and pretty terrible answer. It doesn't recurse at all, doesn't indent, uses `var` and `alert` etc. – Dan Dascalescu Oct 05 '22 at 19:48
143

console.dir(object):

Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.

Note that the console.dir() feature is non-standard. See MDN Web Docs

Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
Pizzaiola Gorgonzola
  • 2,789
  • 1
  • 17
  • 12
  • 1
    Yes this is a good solution, however it only works as exptected if you want to log only the object (e.g. console.dir(obj)). In case you want to concatenate a sting to the output, it'll give you [object Object]. – Zoman Jan 23 '19 at 16:58
  • 2
    A massive advantage of `console.dir` is that you can still expand and read the values in your console after the variable has been garbage collected. This is described in another [SO article here](https://stackoverflow.com/questions/18776467/why-cant-i-expand-this-event-object-in-the-chrome-console) – Dawson B Apr 06 '20 at 19:12
  • 1
    And one more advantage of `console.dir` is that when you save console to file, all properties are in file as expected. That doesn't happen when using console.log only. – Kepi May 21 '20 at 00:11
104

Try this:

console.log(JSON.stringify(obj))

This will print the stringify version of object. So instead of [object] as an output you will get the content of object.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Abhishek Goel
  • 18,785
  • 11
  • 87
  • 65
  • 11
    `typeerror: Converting circular structure to JSON`? – Kaiden Prince Oct 18 '15 at 23:37
  • @KaidenPrince see this answer for your error: http://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json It is likely a DOM element in your object. If that's the case, you're best attempting to just log to the console in chrome or firefox and inspect there. Otherwise you'd have to strip out all circular elements before the JSON.stringify is called in order for it to work. – Ace Hyzer Oct 28 '15 at 20:55
  • Solution is to simply split into 2 separate commands believe it or not: console.log("id:"); console.log(obj); – Collin Chaffin Mar 28 '17 at 21:57
  • 1
    JSON.stringify does not understand Map – andrej May 04 '21 at 07:21
  • Is this somehow different from the top answer given 5 years earlier? If so, please explain and I'll undo my downvote. – Dan Dascalescu Oct 05 '22 at 19:49
  • Mine is one liner and very simple @DanDascalescu :) – Abhishek Goel Jul 10 '23 at 09:21
68

Well, Firefox (thanks to @Bojangles for detailed information) has Object.toSource() method which prints objects as JSON and function(){}.

That's enough for most debugging purposes, I guess.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
alamar
  • 18,729
  • 4
  • 64
  • 97
  • 1
    Your link to `Object.toSource()` now redirects to `Object.prototype.toString()` - mdn doesn't have anything on toSource as far as I can tell. – sc3000 Mar 26 '23 at 16:40
51

If you want to use alert, to print your object, you can do this:

alert("myObject is " + myObject.toSource());

It should print each property and its corresponding value in string format.

Garry
  • 569
  • 4
  • 2
44

If you would like to see data in tabular format you can use:

console.table(obj);

Table can be sorted if you click on the table column.

You can also select what columns to show:

console.table(obj, ['firstName', 'lastName']);

You can find more information about console.table here

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
40

Function:

var print = function(o){
    var str='';

    for(var p in o){
        if(typeof o[p] == 'string'){
            str+= p + ': ' + o[p]+'; </br>';
        }else{
            str+= p + ': { </br>' + print(o[p]) + '}';
        }
    }

    return str;
}

Usage:

var myObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

$('body').append( print(myObject) );

Example:

http://jsfiddle.net/WilsonPage/6eqMn/

wilsonpage
  • 17,341
  • 23
  • 103
  • 147
39

In NodeJS you can print an object by using util.inspect(obj). Be sure to state the depth or you'll only have a shallow print of the object.

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
astone26
  • 1,222
  • 11
  • 16
34

Simply use

JSON.stringify(obj)

Example

var args_string = JSON.stringify(obj);
console.log(args_string);

Or

alert(args_string);

Also, note in javascript functions are considered as objects.

As an extra note :

Actually you can assign new property like this and access it console.log or display it in alert

foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);
Raza Rafaideen
  • 2,119
  • 1
  • 19
  • 30
  • 1
    The question itself states: "Like when we 'alert' a variable", so that's not really an answer. And also your other option "JSON.stringify(obj)" has already been mentioned in "Nov 27 2010", you're only cluttering this question with duplicates and non-answers. Your point about assigning new properties is also senseless in this context. – Paul Dec 11 '18 at 15:34
  • Is this materially different from the top answer given 5 years earlier? If so, please explain and I'll undo my downvote. – Dan Dascalescu Oct 05 '22 at 19:49
24

Here's a way to do it:

console.log("%o", obj);
Anton Harniakou
  • 855
  • 6
  • 13
  • In the context of Chrome-dev-tool, google did mentioned this in this [link](https://developers.google.com/web/tools/chrome-devtools/console/console-write). referring to the section "String substitution and formatting" – chaco Jun 15 '18 at 09:30
  • I saw it in [mdn docs](https://developer.mozilla.org/en-US/docs/Web/API/console#Outputting_text_to_the_console). – Anton Harniakou Jun 15 '18 at 12:35
  • I routinely use the following as a debug statement. console.log("id-str %o",{obj1:obj1,obj2:obj2,...}); The debug window identifies each object and I can drill down on those that are interesting. – Steve Pritchard Jan 15 '22 at 21:52
24

NB: In these examples, yourObj defines the object you want to examine.

First off my least favorite yet most utilized way of displaying an object:

This is the defacto way of showing the contents of an object

console.log(yourObj)

will produce something like : enter image description here

I think the best solution is to look through the Objects Keys, and then through the Objects Values if you really want to see what the object holds...

console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));

It will output something like : enter image description here (pictured above: the keys/values stored in the object)

There is also this new option if you're using ECMAScript 2016 or newer:

Object.keys(yourObj).forEach(e => console.log(`key=${e}  value=${yourObj[e]}`));

This will produce neat output : enter image description here The solution mentioned in a previous answer: console.log(yourObj) displays too many parameters and is not the most user friendly way to display the data you want. That is why I recommend logging keys and then values separately.

Next up :

console.table(yourObj)

Someone in an earlier comment suggested this one, however it never worked for me. If it does work for someone else on a different browser or something, then kudos! Ill still put the code here for reference! Will output something like this to the console : enter image description here

Max Alexander Hanna
  • 3,388
  • 1
  • 25
  • 35
23

To print the full object with Node.js with colors as a bonus:

console.dir(object, {depth: null, colors: true})

Colors are of course optional, 'depth: null' will print the full object.

The options don't seem to be supported in browsers.

References:

https://developer.mozilla.org/en-US/docs/Web/API/Console/dir

https://nodejs.org/api/console.html#console_console_dir_obj_options

jpoppe
  • 2,228
  • 24
  • 25
19

Use this:

console.log('print object: ' + JSON.stringify(session));
Walter Caraza
  • 911
  • 1
  • 10
  • 19
18

As it was said before best and most simply way i found was

var getPrintObject=function(object)
{
    return JSON.stringify(object);
}
yonia
  • 1,681
  • 1
  • 14
  • 12
15

(This has been added to my library at GitHub)

Reinventing the wheel here! None of these solutions worked for my situation. So, I quickly doctored up wilsonpage's answer. This one is not for printing to screen (via console, or textfield or whatever). It does work fine in those situations and works just fine as the OP requested, for alert. Many answers here do not address using alert as the OP requested. Anyhow, It is, however, formatted for data transport. This version seems to return a very similar result as toSource(). I've not tested against JSON.stringify, but I assume this is about the same thing. This version is more like a poly-fil so that you can use it in any environment. The result of this function is a valid Javascript object declaration.

I wouldn't doubt if something like this was already on SO somewhere, but it was just shorter to make it than to spend a while searching past answers. And since this question was my top hit on google when I started searching about this; I figured putting it here might help others.

Anyhow, the result from this function will be a string representation of your object, even if your object has embedded objects and arrays, and even if those objects or arrays have even further embedded objects and arrays. (I heard you like to drink? So, I pimped your car with a cooler. And then, I pimped your cooler with a cooler. So, your cooler can drink, while your being cool.)

Arrays are stored with [] instead of {} and thus dont have key/value pairs, just values. Like regular arrays. Therefore, they get created like arrays do.

Also, all string (including key names) are quoted, this is not necessary unless those strings have special characters (like a space or a slash). But, I didn't feel like detecting this just to remove some quotes that would otherwise still work fine.

This resulting string can then be used with eval or just dumping it into a var thru string manipulation. Thus, re-creating your object again, from text.

function ObjToSource(o){
    if (!o) return 'null';
    var k="",na=typeof(o.length)=="undefined"?1:0,str="";
    for(var p in o){
        if (na) k = "'"+p+ "':";
        if (typeof o[p] == "string") str += k + "'" + o[p]+"',";
        else if (typeof o[p] == "object") str += k + ObjToSource(o[p])+",";
        else str += k + o[p] + ",";
    }
    if (na) return "{"+str.slice(0,-1)+"}";
    else return "["+str.slice(0,-1)+"]";
}

Let me know if I messed it all up, works fine in my testing. Also, the only way I could think of to detect type array was to check for the presence of length. Because Javascript really stores arrays as objects, I cant actually check for type array (there is no such type!). If anyone else knows a better way, I would love to hear it. Because, if your object also has a property named length then this function will mistakenly treat it as an array.

EDIT: Added check for null valued objects. Thanks Brock Adams

EDIT: Below is the fixed function to be able to print infinitely recursive objects. This does not print the same as toSource from FF because toSource will print the infinite recursion one time, where as, this function will kill it immediately. This function runs slower than the one above, so I'm adding it here instead of editing the above function, as its only needed if you plan to pass objects that link back to themselves, somewhere.

const ObjToSource=(o)=> {
    if (!o) return null;
    let str="",na=0,k,p;
    if (typeof(o) == "object") {
        if (!ObjToSource.check) ObjToSource.check = new Array();
        for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}';
        ObjToSource.check.push(o);
    }
    k="",na=typeof(o.length)=="undefined"?1:0;
    for(p in o){
        if (na) k = "'"+p+"':";
        if (typeof o[p] == "string") str += k+"'"+o[p]+"',";
        else if (typeof o[p] == "object") str += k+ObjToSource(o[p])+",";
        else str += k+o[p]+",";
    }
    if (typeof(o) == "object") ObjToSource.check.pop();
    if (na) return "{"+str.slice(0,-1)+"}";
    else return "["+str.slice(0,-1)+"]";
}

Test:

var test1 = new Object();
test1.foo = 1;
test1.bar = 2;

var testobject = new Object();
testobject.run = 1;
testobject.fast = null;
testobject.loop = testobject;
testobject.dup = test1;

console.log(ObjToSource(testobject));
console.log(testobject.toSource());

Result:

{'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}}
({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})

NOTE: Trying to print document.body is a terrible example. For one, FF just prints an empty object string when using toSource. And when using the function above, FF crashes on SecurityError: The operation is insecure.. And Chrome will crash on Uncaught RangeError: Maximum call stack size exceeded. Clearly, document.body was not meant to be converted to string. Because its either too large, or against security policy to access certain properties. Unless, I messed something up here, do tell!

Pimp Trizkit
  • 19,142
  • 5
  • 25
  • 39
  • Crash prone. Try `ObjToSource(document.body)`, for example. – Brock Adams Dec 28 '12 at 22:34
  • ok, I found the issue. I was not checking for null valued objects. That is fixed now. But, you still cant do `ObjToSource(document.body)` because of infinite recursion. Even `document.body.toSource()` in FireFox returns an empty object. – Pimp Trizkit Dec 28 '12 at 23:35
  • @BrockAdams - There now its fixed for infinite recursion, however `document.body` is still not printable. See NOTE. – Pimp Trizkit Dec 29 '12 at 01:57
  • `document.body` was just a shortcut to pointing out some big problems. You've now fixed the worst of those and I already upvoted. (Although, I do believe that a different approach could handle `document.body`. Most of the answers here would not do well against it either.) – Brock Adams Dec 29 '12 at 02:17
  • Well, if you (or anyone else) got any ideas of how to get past the fact that such a large object will fill up the stack during recursion or bypass security restrictions. I would love to hear it. Thanks for the vote! – Pimp Trizkit Dec 29 '12 at 02:21
  • You said, "fixed the worse of those". Care to enlighten me as to what other problems there are? I would like to make it right, even for the small problems. – Pimp Trizkit Dec 29 '12 at 02:33
  • Replace "fixed the worse of those", with "All the problems that I identified at a glance". I did not analyze or test the code in depth as it's not quite what I'm looking for. I didn't say "fixed all problems" because I suspect that such code *should* be able to handle `document.body`, as Firebug does. – Brock Adams Dec 29 '12 at 03:32
  • Ah, gotcha. Well, if you ever find a specific issue. Or come across a way to handle these last two points (stackoverflow, security restrictions), please let me know. – Pimp Trizkit Dec 29 '12 at 04:15
  • Sadly, this answer does not add any indentation. The output is all one single line. – posfan12 Feb 21 '20 at 08:45
  • @posfan12 - Yes, as mentioned in the description, it was mainly made for data transport. For example, you can push it thru `eval` to get your object back. But it does still work with `alert`. – Pimp Trizkit Feb 21 '20 at 16:23
  • @hmijailmournsresignees - If reinventing the wheel is never good, then we would never have rubber tires, and trains. I didn't do it for lazyness. It would have taken me less than a minute to google up `JSON.stringify` if I wanted to be lazy. On the contrary, I spend hard working time on this function. It even gets some traffic on github. JavaScript is finding it's place in more and more interesting environments, this function is a good polyfil for those situations. Plus it can be used as a working solution for the OP. This is also not the only reinvention of pagewil's answer on here. – Pimp Trizkit Jun 24 '20 at 23:03
14

If you would like to print the object of its full length, can use

console.log(require('util').inspect(obj, {showHidden: false, depth: null})

If you want to print the object by converting it to the string then

console.log(JSON.stringify(obj));

sreepurna
  • 1,562
  • 2
  • 17
  • 32
  • you would need to add the `JSON.stringify` when you try to concatenate with a string object. If you use `console.log(object)`, it should pretty print the contents of the object – Satadru Biswas Aug 01 '17 at 22:36
11

I needed a way to recursively print the object, which pagewil's answer provided (Thanks!). I updated it a little bit to include a way to print up to a certain level, and to add spacing so that it is properly indented based on the current level that we are in so that it is more readable.

// Recursive print of object
var print = function( o, maxLevel, level ) {
    if ( typeof level == "undefined" ) {
        level = 0;
    }
    if ( typeof level == "undefined" ) {
        maxLevel = 0;
    }

    var str = '';
    // Remove this if you don't want the pre tag, but make sure to remove
    // the close pre tag on the bottom as well
    if ( level == 0 ) {
        str = '<pre>';
    }

    var levelStr = '';
    for ( var x = 0; x < level; x++ ) {
        levelStr += '    ';
    }

    if ( maxLevel != 0 && level >= maxLevel ) {
        str += levelStr + '...</br>';
        return str;
    }

    for ( var p in o ) {
        if ( typeof o[p] == 'string' ) {
            str += levelStr +
                p + ': ' + o[p] + ' </br>';
        } else {
            str += levelStr +
                p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>';
        }
    }

    // Remove this if you don't want the pre tag, but make sure to remove
    // the open pre tag on the top as well
    if ( level == 0 ) {
        str += '</pre>';
    }
    return str;
};

Usage:

var pagewilsObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

// Recursive of whole object
$('body').append( print(pagewilsObject) ); 

// Recursive of myObject up to 1 level, will only show name 
// and that there is a contact object
$('body').append( print(pagewilsObject, 1) ); 
mmaclaurin
  • 1,412
  • 1
  • 13
  • 18
megaboss98
  • 911
  • 1
  • 8
  • 9
9

You can also use ES6 template literal concept to display the content of a JavaScript object in a string format.

alert(`${JSON.stringify(obj)}`);

const obj  = {
  "name" : "John Doe",
  "habbits": "Nothing",
};
alert(`${JSON.stringify(obj)}`);
Ritu
  • 714
  • 6
  • 14
  • This doesn't really any value beyond the `JSON.stringify` answer given in 2010. The syntax looks more cryptic than `alert(JSON.stringify(obj));`, and template literals are beyond the scope of the question. – Dan Dascalescu Oct 05 '22 at 19:54
6

I always use console.log("object will be: ", obj, obj1). this way I don't need to do the workaround with stringify with JSON. All the properties of the object will be expanded nicely.

nils petersohn
  • 2,317
  • 2
  • 25
  • 27
6

Another way of displaying objects within the console is with JSON.stringify. Checkout the below example:

var gandalf = {
  "real name": "Gandalf",
  "age (est)": 11000,
  "race": "Maia",
  "haveRetirementPlan": true,
  "aliases": [
    "Greyhame",
    "Stormcrow",
    "Mithrandir",
    "Gandalf the Grey",
    "Gandalf the White"
  ]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));
Socrates
  • 8,724
  • 25
  • 66
  • 113
Kean Amaral
  • 5,503
  • 2
  • 16
  • 9
5

Javascript Function

<script type="text/javascript">
    function print_r(theObj){ 
       if(theObj.constructor == Array || theObj.constructor == Object){ 
          document.write("<ul>") 
          for(var p in theObj){ 
             if(theObj[p].constructor == Array || theObj[p].constructor == Object){ 
                document.write("<li>["+p+"] => "+typeof(theObj)+"</li>"); 
                document.write("<ul>") 
                print_r(theObj[p]); 
                document.write("</ul>") 
             } else { 
                document.write("<li>["+p+"] => "+theObj[p]+"</li>"); 
             } 
          } 
          document.write("</ul>") 
       } 
    } 
</script>

Printing Object

<script type="text/javascript">
print_r(JAVACRIPT_ARRAY_OR_OBJECT);
</script> 

via print_r in Javascript

Mukesh Chapagain
  • 25,063
  • 15
  • 119
  • 120
  • I'm not sure if this is a bug in the js.do example I'm using, but this only seems to output the first full "branch" of the tree. ie it follows the first reference of the first reference... ad infinitum – Jon Story Feb 12 '15 at 12:47
5
var list = function(object) {
   for(var key in object) {
     console.log(key);
   }
}

where object is your object

or you can use this in chrome dev tools, "console" tab:

console.log(object);

user3632930
  • 311
  • 2
  • 8
  • I think your answer is incomplete. (not me that cause downvote) This, yet, only print the key.. – Abdillah Apr 22 '15 at 09:13
  • 1
    thanks for your answer, it has inspired me to do this: `console.log(Object.keys(object));` while I know that only prints the properties keys, it is enough to me for my purposes ;) – Wilson Aug 05 '15 at 15:17
5

Assume object obj = {0:'John', 1:'Foo', 2:'Bar'}

Print object's content

for (var i in obj){
    console.log(obj[i], i);
}

Console output (Chrome DevTools) :

John 0
Foo 1
Bar 2

Hope that helps!

incalite
  • 3,077
  • 3
  • 26
  • 32
5

I prefer using console.table for getting clear object format, so imagine you have this object:

const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};

And you will you see a neat and readable table like this below: console.table

Alireza
  • 100,211
  • 27
  • 269
  • 172
4

Circular references solution

To make string without redundant information from object which contains duplicate references (references to same object in many places) including circular references, use JSON.stringify with replacer (presented in snippet) as follows

let s = JSON.stringify(obj, refReplacer(), 4);

function refReplacer() {
  let m = new Map(), v= new Map(), init = null;

  return function(field, value) {
    let p= m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field); 
    let isComplex= value===Object(value)
    
    if (isComplex) m.set(value, p);  
    
    let pp = v.get(value)||'';
    let path = p.replace(/undefined\.\.?/,'');
    let val = pp ? `#REF:${pp[0]=='[' ? '$':'$.'}${pp}` : value;
    
    !init ? (init=value) : (val===init ? val="#REF:$" : 0);
    if(!pp && isComplex) v.set(value, path);
   
    return val;
  }
}




// ---------------
// TEST
// ---------------

// gen obj with duplicate references
let a = { a1: 1, a2: 2 };
let b = { b1: 3, b2: "4" };
let obj = { o1: { o2:  a  }, b, a }; // duplicate reference
a.a3 = [1,2,b];                      // circular reference
b.b3 = a;                            // circular reference


let s = JSON.stringify(obj, refReplacer(), 4);

console.log(s);
alert(s);

This solution based on this (more info there) create JSONPath like path for each object value and if same object occurs twice (or more) it uses reference with this path to reference that object e.g. #REF:$.bar.arr[3].foo (where $ means main object) instead 'render' whole object (which is less redundant)

BONUS: inversion

function parseRefJSON(json) {
  let objToPath = new Map();
  let pathToObj = new Map();
  let o = JSON.parse(json);
  
  let traverse = (parent, field) => {
    let obj = parent;
    let path = '#REF:$';

    if (field !== undefined) {
      obj = parent[field];
      path = objToPath.get(parent) + (Array.isArray(parent) ? `[${field}]` : `${field?'.'+field:''}`);
    }

    objToPath.set(obj, path);
    pathToObj.set(path, obj);
    
    let ref = pathToObj.get(obj);
    if (ref) parent[field] = ref;

    for (let f in obj) if (obj === Object(obj)) traverse(obj, f);
  }
  
  traverse(o);
  return o;
}



// ------------
// TEST
// ------------

let s = `{
    "o1": {
        "o2": {
            "a1": 1,
            "a2": 2,
            "a3": [
                1,
                2,
                {
                    "b1": 3,
                    "b2": "4",
                    "b3": "#REF:$.o1.o2"
                }
            ]
        }
    },
    "b": "#REF:$.o1.o2.a3[2]",
    "a": "#REF:$.o1.o2"
}`;

console.log('Open Chrome console to see nested fields');
let obj = parseRefJSON(s);
console.log(obj);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
3

A little helper function I always use in my projects for simple, speedy debugging via the console. Inspiration taken from Laravel.

/**
 * @param variable mixed  The var to log to the console
 * @param varName string  Optional, will appear as a label before the var
 */
function dd(variable, varName) {
    var varNameOutput;

    varName = varName || '';
    varNameOutput = varName ? varName + ':' : '';

    console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}

Usage

dd(123.55); outputs:
enter image description here

var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj'); 

enter image description here

George Kagan
  • 5,913
  • 8
  • 46
  • 50
3

The console.log() does a great job of debugging objects, but if you are looking to print the object to the page content, here's the simplest way that I've come up with to mimic the functionality of PHP's print_r(). A lot these other answers want to reinvent the wheel, but between JavaScript's JSON.stringify() and HTML's <pre> tag, you get exactly what you are looking for.

var obj = { name: 'The Name', contact: { email: 'thename@gmail.com', tel: '123456789' }};
$('body').append('<pre>'+JSON.stringify(obj, null, 4)+'</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Scott
  • 115
  • 1
  • 6
2

i used pagewil's print method, and it worked very nicely.

here is my slightly extended version with (sloppy) indents and distinct prop/ob delimiters:

var print = function(obj, delp, delo, ind){
    delp = delp!=null ? delp : "\t"; // property delimeter
    delo = delo!=null ? delo : "\n"; // object delimeter
    ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
    var str='';

    for(var prop in obj){
        if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
          var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
          str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
        }else{
          str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
        }
    }
    return str;
};
bitless
  • 418
  • 4
  • 7
2

Another modification of pagewils code... his doesn't print out anything other than strings and leaves the number and boolean fields blank and I fixed the typo on the second typeof just inside the function as created by megaboss.

var print = function( o, maxLevel, level )
{
    if ( typeof level == "undefined" )
    {
        level = 0;
    }
    if ( typeof maxlevel == "undefined" )
    {
        maxLevel = 0;
    }

    var str = '';
    // Remove this if you don't want the pre tag, but make sure to remove
    // the close pre tag on the bottom as well
    if ( level == 0 )
    {
        str = '<pre>';   // can also be <pre>
    }

    var levelStr = '<br>';
    for ( var x = 0; x < level; x++ )
    {
        levelStr += '    ';   // all those spaces only work with <pre>
    }

    if ( maxLevel != 0 && level >= maxLevel )
    {
        str += levelStr + '...<br>';
        return str;
    }

    for ( var p in o )
    {
        switch(typeof o[p])
        {
          case 'string':
          case 'number':    // .tostring() gets automatically applied
          case 'boolean':   // ditto
            str += levelStr + p + ': ' + o[p] + ' <br>';
            break;

          case 'object':    // this is where we become recursive
          default:
            str += levelStr + p + ': [ <br>' + print( o[p], maxLevel, level + 1 ) + levelStr + ']</br>';
            break;
        }
    }

    // Remove this if you don't want the pre tag, but make sure to remove
    // the open pre tag on the top as well
    if ( level == 0 )
    {
        str += '</pre>';   // also can be </pre>
    }
    return str;
};
ppetree
  • 826
  • 3
  • 15
  • 31
2

Here's function.

function printObj(obj) {
console.log((function traverse(tab, obj) {
    let str = "";
    if(typeof obj !== 'object') {
        return obj + ',';
    }
    if(Array.isArray(obj)) {            
        return '[' + obj.map(o=>JSON.stringify(o)).join(',') + ']' + ',';
    }
    str = str + '{\n';
    for(var p in obj) {
        str = str + tab + ' ' + p + ' : ' + traverse(tab+' ', obj[p]) +'\n';
    }
    str = str.slice(0,-2) + str.slice(-1);                
    str = str + tab + '},';
    return str;
}('',obj).slice(0,-1)))};

It can show object using tab indent with readability.

Juho Sung
  • 59
  • 5
2

If you're looking for something that can return a prettified string of any javascript object, check out https://github.com/fresheneesz/beautinator . An example:

var result = beautinator({ "font-size": "26px","font-family": "'Open Sans', sans-serif",color: "white", overflow: "hidden",padding: "4px 4px 4px 8px",Text: { display: "block", width: "100%","text-align": "center", "padding-left": "2px","word-break": "break-word"}})
console.log(result)

Results in:

{ "font-size": "26px",
  "font-family": "'Open Sans', sans-serif",
  color: "white", overflow: "hidden",
  padding: "4px 4px 4px 8px",
  Text: { display: "block", width: "100%",
          "text-align": "center", "padding-left": "2px",
          "word-break": "break-word"
  }
}

It even works if there are functions in your object.

B T
  • 57,525
  • 34
  • 189
  • 207
1

A simple way to show the contents of the object is using console.log as shown below

console.log("Object contents are ", obj);

Please note that I am not using '+' to concatenate the object. If I use '+' than I will only get the string representation if object, something like [Object object].

Vikram
  • 1,617
  • 5
  • 17
  • 37
1

In ES2015, using the shorthand property declaration syntax for object literals, you can log objects while also concisely preserving your variable names:

console.log("bwib:", bwib, "bwab:", bwab, "bwob": bwob) // old way A
console.log({bwib: bwib, bwab: bwab, bwob: bwob})       // old way B

console.log({bwib, bwab, bwob})                         // ES2015+ way

Demonstration in Firefox Console

dsharhon
  • 489
  • 3
  • 11
0

Try this one:

var object = this.window;
console.log(object,'this is window object');

Output:

enter image description here

Elshan
  • 7,339
  • 4
  • 71
  • 106
0

It will not work in a browser and you might only need this in case you want to get valid JS representation for your object and not a JSON. It just runs node inline evaluation

var execSync = require('child_process').execSync

const objectToSource = (obj) =>
  execSync('node -e \'console.log(JSON.parse(`' + JSON.stringify(obj) + '`))\'', { encoding: 'utf8' })

console.log(objectToSource({ a: 1 }))
Thirumalai Parthasarathi
  • 4,541
  • 1
  • 25
  • 43
Yuriy Naydenov
  • 1,875
  • 1
  • 13
  • 31
-1

The simplest answer

I am astounded this doesn't have a simpler answer, just a bunch of people repeating the exact same 2 things and others with unreadable code...

Here you go. If you just need the object as a string (no nested levels):

function prettyStringifyObject(obj: Record < any, any > ) {
  let result = ''
  for (const key in obj) {
    result = `${result}${result !== '' ? ', ' : ''}${key}: ${Array.isArray(obj[key]) ? `[${obj[key]}]` : obj[key]}`
  }
  return `{${result}}`
}

Tests

Test with

const someTestObject = {
  data: [1, 2, 3, "4"],
  aString: "awdasdyhblhyb",
  aBoolean: true,
  aNumber: 50,
  aNull: null
  aNestedObject: {
    someOtherData: [],
    isNested: true
  }
}

console.log(prettyStringifyObject(someTestObject))

Result:

"{data: [1,2,3,4], aString: awdasdyhblhyb, aBoolean: true, aNumber: 50, aNull: null, aNestedObject: [object Object]}"

You can check the JSFiddle I made here

Bosco Domingo
  • 176
  • 2
  • 7
-2

You may use my function .
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

It seems that a simple for...in can't solve the problem especially when we want to tackle apart from custom, host , native or CSSOM objects. Besides, we are talking about debugging here and who knows when and where we'll need it!

My small library can handle objects like this one:

    obj2
     |__ foo = 'bar'
     |__ loop2 = obj2
     |            :
     |__ another = obj1
                    |__ a1 = 1
                    |__ b1 = 'baz'
                    |__ loop1 = obj1
                    |            :
                    |__ c1 = true
                    |__ d1 = ''
                    |__ e1 = [1,2,3]

and present them colorful and with identation like:

  1. 0, foo, 'bar'
  2. 0, loop2, 'contains a circular reference to object at index 0'
  3. 0, another, 'object'
  4. 1, a1, 1
  5. 1, b1, 'baz'
  6. 1, loop1, 'contains a circular reference to object at index 2'
  7. 1, c1, 'true'
  8. 1, d1, ''
  9. 1, e1, [1,2,3]

but see there:

  1. https://github.com/centurianii/jsdebug
  2. http://jsfiddle.net/centurianii/92Cmk/36/

With some precautions even document.body is parsed!

centurian
  • 1,168
  • 13
  • 25