Wednesday, December 27, 2017

How can I display a JavaScript object?

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.)

Edit (17/02/2014): Use a custom JSON.stringify replacer if you encounter this Javascript error
"Uncaught TypeError: Converting circular structure to JSON"

No comments:

Post a Comment