How can I convert a JavaScript object into a string?
Example:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
Output:
Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(
How can I convert a JavaScript object into a string?
Example:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
Output:
Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(
If all you want is to simply get a string output, then this should work:
String(object)
None of the solutions here worked for me. JSON.stringify seems to be what a lot of people say, but it cuts out functions and seems pretty broken for some objects and arrays I tried when testing it.
I made my own solution which works in Chrome at least. Posting it here so anyone that looks this up on Google can find it.
EDIT: I know this code can be improved but just never got around to doing it. User andrey suggested an improvement here with the comment:
Use that at your own risk as I haven't verified it at all. Feel free to suggest any additional improvements as a comment.
If you just want to see the object for debugging, you can use
Take a look at the jQuery-JSON plugin
At its core, it uses JSON.stringify but falls back to its own parser if the browser doesn't implement it.
EDIT Do not use this answer as it does not work in Internet Explorer. Use Gary Chambers solution.
toSource() is the function you are looking for which will write it out as JSON.