How can I display a JavaScript object?

maxjackie picture maxjackie · Jun 5, 2009 · Viewed 1.9M times · Source

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.

Answer

Sandeep picture Sandeep · Nov 27, 2010

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"