Why console.log(window) works but JSON.stringify(window) doesn't work, and how can I beat that?
console.log, javascript, json
Solution
That's because `window` has circular references (for instance, in most cases `window.self` refers to `window`) and then it cannot be converted to JSON, otherwise it would turn into an infinite loop.
This may happen on any object, not only on `window`:
var foo = {
bar: 'bar'
};
JSON.stringify(foo); // works fine
var foo = {
bar: foo
};
JSON.stringify(foo); // circular reference -> crashes
Problem
If I type in console: ``` console.log(window) ``` I get all the objects in `window` with expand buttons. But if I try the same with: ``` JSON.stringify(window) ``` I get in Firefox: ``` Error: Permission denied to access property 'toJSON' ``` And in chrome: ``` TypeError: Converting circular structure to JSON ``` Is this the only case where this happen? And given that `console.log()` and `JSON.stringify()` work differently, can I access and still stringify objects that `console.log()` manages to display?