Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display a JavaScript object?

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.

like image 425
maxjackie Avatar asked Jun 05 '09 19:06

maxjackie


People also ask

How do you represent an object in JavaScript?

Using an Object Literal This is the easiest way to create a JavaScript Object. Using an object literal, you both define and create an object in one statement. An object literal is a list of name:value pairs (like age:50) inside curly braces {}.

How do I print an object in console?

Answer: Use console. log() or JSON. stringify() Method This method will print the object in browser console.


1 Answers

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" 
like image 147
Sandeep Avatar answered Oct 06 '22 10:10

Sandeep