How to Convert Object to String in JavaScript

In JavaScript, Objects are variables that contain many values. The values are written as name: value pairs. A JavaScript string stores a series of characters like “Homer Simpson”. In this article, we will see the conversion of Object to String.

Object to String in JavaScript

To convert an Object to String in JavaScript, use the JSON.stringify() function. The JSON.stringify() is a built-in JavaScript method that converts objects into strings.

To stringify the JavaScript Object, use the JSON.stringify() method. Most modern browsers support the stringify() method natively. The JSON.stringify() method is the canonical approach to convert a JavaScript Object to JSON too.

The JSON.stringify() is used by many frameworks and libraries under the hood. For example, the Express web framework uses the res.json() function, and The Axios library provides the post() method, which uses stringify() under the hood, and Webpack stats all call JSON.stringify().

Syntax

JSON.stringify(obj, replacer, space)

Arguments

Obj: The object argument is required. It is the value to convert to a string.

Replacer: It is an optional argument. Either a function or an array is used to transform the result. 

Space: It is optional. Either a String or a Number.

Implementation of JSON.stringify()

To create an Object literal, use the { } and add key-values to the Object.

const obj = { name: "Krunal", age: 28, city: "Rajkot" }

const jsonData = JSON.stringify(obj)

console.log(jsonData)

console.log(typeof(jsonData))

Output

{"name":"Krunal", "age":28, "city":"Rajkot"}

string

You can see that we converted the input Object into a String

To check the data type of any variable in JavaScript, use the typeof() method.

Errors and Exceptions

JSON.stringify() function throws an error when it detects a cyclical object. If an object obj has a property whose value is obj, JSON.stringify() will throw the error.

const obj = {};

// Cyclical object that references itself
obj.prop = obj;

console.log(JSON.stringify(obj))

Output

TypeError: Converting circular structure to JSON

This is the only case where JSON.stringify() throws an exception.

That’s it for this tutorial.

See also

JavaScript array to string

JavaScript string to boolean

Leave a Comment