Convert object to string javascript

JSON methods are quite inferior to the Gecko engine .toSource() primitive.

See the SO article response for comparison tests.

Also, the answer above refers to http://forums.devshed.com/javascript-development-115/tosource-with-arrays-in-ie-386109.html which, like JSON, (which the other article http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json uses via "ExtJs JSON encode source code") cannot handle circular references and is incomplete. The code below shows it's (spoof's) limitations (corrected to handle arrays and objects without content).

(direct link to code in //forums.devshed.com/ ... /tosource-with-arrays-in-ie-386109)

javascript:
Object.prototype.spoof=function(){
    if (this instanceof String){
      return '(new String("'+this.replace(/"/g, '\\"')+'"))';
    }
    var str=(this instanceof Array)
        ? '['
        : (this instanceof Object)
            ? '{'
            : '(';
    for (var i in this){
      if (this[i] != Object.prototype.spoof) {
        if (this instanceof Array == false) {
          str+=(i.match(/\W/))
              ? '"'+i.replace('"', '\\"')+'":'
              : i+':';
        }
        if (typeof this[i] == 'string'){
          str+='"'+this[i].replace('"', '\\"');
        }
        else if (this[i] instanceof Date){
          str+='new Date("'+this[i].toGMTString()+'")';
        }
        else if (this[i] instanceof Array || this[i] instanceof Object){
          str+=this[i].spoof();
        }
        else {
          str+=this[i];
        }
        str+=', ';
      }
    };
    str=/* fix */(str.length>2?str.substring(0, str.length-2):str)/* -ed */+(
        (this instanceof Array)
        ? ']'
        : (this instanceof Object)
            ? '}'
            : ')'
    );
    return str;
  };
for(i in objRA=[
    [   'Simple Raw Object source code:',
        '[new Array, new Object, new Boolean, new Number, ' +
            'new String, new RegExp, new Function, new Date]'   ] ,

    [   'Literal Instances source code:',
        '[ [], {}, true, 1, "", /./, function(){}, new Date() ]'    ] ,

    [   'some predefined entities:',
        '[JSON, Math, null, Infinity, NaN, ' +
            'void(0), Function, Array, Object, undefined]'      ]
    ])
alert([
    '\n\n\ntesting:',objRA[i][0],objRA[i][1],
    '\n.toSource()',(obj=eval(objRA[i][1])).toSource(),
    '\ntoSource() spoof:',obj.spoof()
].join('\n'));

which displays:

testing:
Simple Raw Object source code:
[new Array, new Object, new Boolean, new Number, new String,
          new RegExp, new Function, new Date]

.toSource()
[[], {}, (new Boolean(false)), (new Number(0)), (new String("")),
          /(?:)/, (function anonymous() {}), (new Date(1303248037722))]

toSource() spoof:
[[], {}, {}, {}, (new String("")),
          {}, {}, new Date("Tue, 19 Apr 2011 21:20:37 GMT")]

and

testing:
Literal Instances source code:
[ [], {}, true, 1, "", /./, function(){}, new Date() ]

.toSource()
[[], {}, true, 1, "", /./, (function () {}), (new Date(1303248055778))]

toSource() spoof:
[[], {}, true, 1, ", {}, {}, new Date("Tue, 19 Apr 2011 21:20:55 GMT")]

and

testing:
some predefined entities:
[JSON, Math, null, Infinity, NaN, void(0), Function, Array, Object, undefined]

.toSource()
[JSON, Math, null, Infinity, NaN, (void 0),
       function Function() {[native code]}, function Array() {[native code]},
              function Object() {[native code]}, (void 0)]

toSource() spoof:
[{}, {}, null, Infinity, NaN, undefined, {}, {}, {}, undefined]

Have you ever encountered a situation where you want to send some data to the web server that is in object format? If yes, first convert it to a string and then head towards the mentioned operation. With the help of JavaScript methods, an object can be converted to a string without any hassle.

Don’t know the method of converting an object to string in JavaScript? No worries! This write-up will explain different ways for an object to string conversion. So, let’s start!

To perform the object to string conversion, you can follow any of the below-given approaches:

  • Using JSON.Stringify() method
  • Using toString() method
  • Using String() function

We will explain each of the methods mentioned above in the next sections.

Method 1: Converting object to string in JavaScript using JSON.stringify() method

Stringification” is the process of converting a JavaScript object to a string. This operation is performed when you want to serialize data to string for sending it to some web server or storing it in a database. According to the JavaScript standard, the “JSON.stringify()” method is utilized to convert the specified object into a string with the help of Stringification.

Syntax

JSON.stringify(value, replacer, space)

Here, “value” refers to the “object” that needs to be converted into “string”, “replacer” is an optional parameter that represents a modification function or an array used as a filter, and “space” is another optional parameter that is utilized for controlling the space sequence in the final string.

Example
First of all, we will create an “employee” object having the following key-value pairs:

const employee= {
  name: 'Max',
  age: 25
}

In the next step, we will check the initial “type” of the “employee” object:

console.log("Type of employee: " +typeof(employee));

The given output signifies that “employee” is of “object” type:

Convert object to string javascript

Then, we will use the “JSON.stringify()” method for converting the “employee” object to “string”:

const string = JSON.stringify(employee);
console.log(string);

After conversion, we will again check the type by utilizing the “typeof” operator:

console.log("Type after conversion: " +typeof(string));

As you can see from the output, we have successfully converted the “employee” object to “string”:

Convert object to string javascript

Method 2: Converting object to string in JavaScript using toString() method

JavaScript also offers a built-in method primarily utilized for explicitly converting a data type into a string. The “toString()” method returns the string representation of a number, an array, or a JavaScript object, whereas in the case of the object to string conversion; you have to override the “toString()” method so that it can print out the values of the object’s keys.

Syntax

Here, the “toString()” method converts the “object” and outputs the respective string.

Example
We will now use the “toString()” method to convert the “employee” object to a “string”:

const string = employee.toString();
console.log(string);
console.log("Type after conversion: " +typeof(string));

The output of the given program will print out “[object, Object]” and its type as “string”:

Convert object to string javascript

However, you can override the “toString()” method to return the values of the object properties in a string format.

In the below-given program, the “Employee” object will override the “toString()” method which is inherited from the “Object” base class. This user-defined “toString()” method will return a string containing the values of the “name” and “age” properties of the created “employee” object:

function Employee(name, age) {
this.name= name;
this.age = age;
}
Employee.prototype.toString = function () {
return 'Employee Name: '+this.name + ' Age: '+ this.age;
}

employee = new Employee('Max', 35);
var string = employee.toString();
console.log(string);
console.log("Type after conversion: " +typeof(string));

Now, when the “toString()” method is invoked, it will display the values of the “employee” object properties as string:

Convert object to string javascript

Method 3: Converting object to string in JavaScript using String() function

String()” is another built-in JavaScript function that can be used for converting the value of an object to string. This function accepts a JavaScript “object” as an argument and converts it to the corresponding string.

Syntax

Here, the “String()” function converts the added “object” to its corresponding “string”.

Example
In the below-given example, we will invoke the “String()” function to convert the “employee” object into a “string”:

var string = String(employee);
console.log(string);
console.log("Type after conversion: " +typeof(string));

Execution of the above-given code will display the “string” as “[object Object]” and its type as “string”:

Convert object to string javascript

Similar to “toString()” method, we have to override the “String()” function to return the values of the “employee” object properties as a “string”:

function Employee(name, age) {
this.name= name;
this.age = age;
}
Employee.prototype.String = function () {
return 'Employee Name: '+this.name + ' Age: '+ this.age;
}

employee = new Employee('Max', 35);
var string = employee.String();
console.log(string);
console.log("Type after conversion: " +typeof(string));

The below-given output signifies that now the converted string comprises the values of the “employee” object properties:

Convert object to string javascript

We have compiled different methods for converting an object to string in JavaScript. You can use any of them according to your requirements.

Conclusion

The JSON.stringify() method, toString() method, and String() function are used to convert an object to string in JavaScript. The JavaScript JSON.stringify() method performs the direct object to string conversion, whereas you have to override the toString() method and String() function, so that they can display the object properties value in the converted string. This write-up discussed different ways to convert a JavaScript object to a string.

About the author

Convert object to string javascript

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

How do you turn an object into a string?

Convert Object to String in java using toString() method of Object class or String. valueOf(object) method. Since there are mainly two types of class in java, i.e. user-defined class and predefined class such as StringBuilder or StringBuffer of whose objects can be converted into the string.

How convert JavaScript object to string explain with example?

Method 1: Converting object to string in JavaScript using JSON..
JSON. stringify(value, replacer, space).
const employee= { name: 'Max', ... .
console. log("Type of employee: " +typeof(employee));.
const string = JSON. stringify(employee); ... .
console. ... .
object. ... .
const string = employee. ... .
String(object).

How can we convert an object to JSON string?

These are the following steps to convert a Java object into JSON:.
Create a Maven project..
Add GSON dependency in xml file..
Create Plain Old Java Object to convert into JSON..
Create a Java class to convert the Java object to JSON..

What does JSON Stringify () do?

JSON.stringify() The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.