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:
var obj={
name:'xyz',
Address:'123, Somestreet'
}
var convertedString=JSON.stringify(obj)
console.log("literal object is",obj ,typeof obj);
console.log("converted string :",convertedString);
console.log(" convertedString type:",typeof convertedString);
There is actually one easy option (for recent browsers and Node.js) missing in the existing answers:
console.log('Item: %o', o);
I would prefer this as JSON.stringify()
has certain limitations (e.g. with circular structures).
Keeping it simple with console
, you can just use a comma instead of a +
. The +
will try to convert the object into a string, whereas the comma will display it separately in the console.
Example:
var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o); // :)
Output:
Object { a=1, b=2} // useful
Item: [object Object] // not useful
Item: Object {a: 1, b: 2} // Best of both worlds! :)
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Console.log
stringify-object
is a good npm library made by the yeoman team: https://www.npmjs.com/package/stringify-object
npm install stringify-object
then:
const stringifyObject = require('stringify-object');
stringifyObject(myCircularObject);
Obviously it's interesting only if you have circular object that would fail with JSON.stringify();
If you are using the Dojo javascript framework then there is already a build in function to do this: dojo.toJson() which would be used like so.
var obj = {
name: 'myObj'
};
dojo.toJson(obj);
which will return a string. If you want to convert the object to json data then add a second parameter of true.
dojo.toJson(obj, true);
http://dojotoolkit.org/reference-guide/dojo/toJson.html#dojo-tojson
EDIT Do not use this answer as it works only in some versions of Firefox. No other browsers support it. Use Gary Chambers solution.
toSource() is the function you are looking for which will write it out as JSON.
var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());