How to Convert Object to String

Sometimes, you need to convert a JavaScript object to a plain string that is useful for storing object data in a database. In this tutorial, we will suggest two methods for converting an object to a string.

The JSON.stringify() Method

The JSON.stringify() method is used to convert object to string which is needed to send data over the web server. It converts the set of variables in the object to a JSON string:

var objToStr = {
  siteName: "W3Docs",
  bookName: "Javascript",
  booksCount: 5
};
var myJSON = JSON.stringify(objToStr);
console.log(myJSON);

Output:

{"siteName":"W3Docs", "bookName":"Javascript", "booksCount": 5}
However, this doesn't work if the object has function property.

The toString() Method

The toString() method is also called when you need to convert the object into a string:

var obj = {
  siteName: "W3Docs",
  bookName: "Javascript",
  booksCount: 5
};
function objToString(object) {
  var str = '';
  for (var k in object) {
    if (object.hasOwnProperty(k)) {
      str += k + '::' + object[k] + '\n';
    }
  }
console.log(str);
  return str;
}
objToString(obj);

JSON.Stringify() and toString()

The JSON.stringify() method converts an object or value to a JSON string. JSON.stringify skips some JavaScript-specific objects, such as properties storing undefined, symbolic properties, and function properties.

The toString( ) method is called without arguments and should return a string. The string you return should be based on the value of the object for which the method was called so as to be useful.


Do you find this helpful?

Related articles