Converting an object to a string

user680174 picture user680174 · Apr 10, 2011 · Viewed 1.7M times · Source

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 :(

Answer

Gary Chambers picture Gary Chambers · Apr 10, 2011

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:

var obj = {
  name: 'myObj'
};

JSON.stringify(obj);