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 :(
For non-nested objects:
I would recommend using
JSON.stringify
, which converts the set of the variables in the object to a JSON string. Most modern browsers support this method natively, but for those that don't, you can include a JS version:Sure, to convert an object into a string, you either have to use your own method, such as:
Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578 or http://phpjs.org/functions/var_dump:604
or, if you are not using methods (functions as properties of your object), you may be able to use the new standard (but not implemented in older browsers, though you can find a utility to help with it for them too), JSON.stringify(). But again, that won't work if the object uses functions or other properties which aren't serializable to JSON.
Since Javascript v1.0 works everywhere (even IE) this is a native approach and allows for a very costomised look of your object while debugging and in production https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
Usefull example
Also, as a bonus
1.
2.
I was looking for this, and wrote a deep recursive one with indentation :
Usage :
objToString({ a: 1, b: { c: "test" } })