How to Convert Object to String
Read this JavaScript tutorial and learn about the fastest methods of converting object into string. Read about JSON.stringify() and toString() methods.
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:
Javascript JSON.stringify method
Output:
{"siteName":"W3Docs", "bookName":"Javascript", "booksCount": 5}Note that JSON.stringify() does not throw an error if the object contains function properties; it silently omits them.
The toString() Method
The native Object.prototype.toString() method returns "[object Object]" for plain objects and is not suitable for data serialization. Instead, you can use a custom utility function to convert an object into a string:
Javascript custom toString utility
JSON.Stringify() and toString()
The <kbd class="highlighted">JSON.stringify()</kbd> method converts an object or value to a JSON string. JSON.stringify() skips some JavaScript-specific properties, such as those storing undefined, symbolic keys, and function properties.
The native <kbd class="highlighted">toString()</kbd> method is called without arguments and returns a string representation of the object. For plain objects, it returns "[object Object]", which is not useful for data export. The custom function above demonstrates a practical alternative for serialization.