Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an object to a string

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

like image 276
user680174 Avatar asked Apr 10 '11 15:04

user680174


People also ask

How do you turn an object into a string?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

What method converts an object to a string?

The JavaScript system invokes the toString( ) method to convert an object to a string whenever the object is used in a string context. For example, an object is converted to a string when it is passed to a function that expects a string argument: alert(my_object);

How will you convert a object to a string in Python?

Converting Object to String Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods.


2 Answers

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); 
like image 50
Gary Chambers Avatar answered Oct 11 '22 00:10

Gary Chambers


Use javascript String() function

 String(yourobject); //returns [object Object] 

or stringify()

JSON.stringify(yourobject) 
like image 22
Vikram Pote Avatar answered Oct 10 '22 22:10

Vikram Pote