Console.log is incompatible with JSON.stringify

I have reason to believe that console.log and JSON.stringify can create conflicting representations of the same object, even if they were created in a simple way (see notes).

Situation

In the Google Chrome and Firebug developer tools, I had an obj object that console.log printed as { players: {0: ...}, ...} , and JSON.stringify - { players: {}, ...} . obj.players with both functions {} , so it seems that console.log is the culprit. Could this be asynchronous / non-deterministic in some way?

Additional notes

I’m afraid that I won’t be able to provide much more context, since the code is long for the client as well, but I can try if there is something that could help to figure this out. At the moment, I am forced to stay away from console.log for verification.

It might be useful to know that an object is formed simply from an object literal by manually setting properties, for example, obj.players = {}; obj.players[0] = ... obj.players = {}; obj.players[0] = ...

the code

A sample of what I mean can be seen at http://jsfiddle.net/9dcJP/ .

+8
javascript google-chrome-devtools firebug
source share
2 answers

Why don't you just use console.dir(obj) ? Or use console.log(obj) and then click on exit / expand it?

Also, when I try to execute the following code:

 var obj = {}; obj.players = {}; obj.players[0] = {color: "green"}; obj.players[1] = {color: "blue"}; obj.world = "xyz"; console.log(JSON.stringify(obj)); 

I always (Firefox, Chrome, Opera) get this as output:

 {"players":{"0":{"color":"green"},"1":{"color":"blue"}},"world":"xyz"} 

Also, it looks like your players object is actually an array. Therefore, you are better off creating it as such.

Update: I just noticed that you added a link to the JSFIDDLE demo, which empties the players object immediately after registering it. As far as I know, all web development tools use some kind of asynchronous display, which leads to an empty players object when using console.log(obj) or console.dir(obj) . Thus, Firebug gives the best results by displaying the object correctly using console.dir(obj) .

+11
source share

To answer the question - yes, console.log operations are asynchronous , so you cannot rely on exact values ​​in console - especially if you change the printed object right after calling console.log (for example, you do).

If you remove the line:

 obj.players = {}; 

then the differences between simple console.log and JSON.stringify disappear.

Whereas there is a difference between logging a real object in the developer tool console (console.log (obj) and printing a string version of the object (console.log (JSON.stringify (obj))). Thus, the representation of the object will be still be different.

0
source share

All Articles