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.
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 {}.
Answer: Use console. log() or JSON. stringify() Method This method will print the object in browser console.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With