Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
812 views
Welcome To Ask or Share your Answers For Others

1 Answer

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...