You can use the JSON.stringify() method to convert a JavaScript object to a JSON string.

Example:

let object = {name: "John", age: 30, city: "New York"};
let jsonString = JSON.stringify(object);
console.log(jsonString);

The JSON.stringify() method can also take two additional parameters:

  • The first parameter is a replacer function that alters the behavior of the stringification.
  • The second parameter is a String or Number value to use as white space in the returned string.
let jsonString = JSON.stringify(object,null, 2);
console.log(jsonString);

This will add 2 spaces as white space in the returned string.

Also Read:

Categorized in: