How to Convert an Object to JSON in JavaScript

To convert an Object to a JSON string in JavaScript, you can use the built-in “JSON.stringify()” method. It takes a JavaScript object as its argument and returns a JSON string representation of the object.

Example 1

const obj = {
  name: 'Niva',
  age: 30,
  city: 'Perth'
};

const jsonString = JSON.stringify(obj);

console.log(jsonString);

Output

{"name":"Niva","age":30,"city":"Perth"}

In this example, we used the “JSON.stringify()” method to convert the obj variable, a JavaScript object, into a JSON string. The resulting JSON string is ‘{“name”:”Niva”,”age”:30,”city”:”Perth”}’.

Example 2

The JSON.stringify() function takes two optional parameters: a replacer function or an array of property names and a space parameter for formatting. The replacer function or array can be used to filter or modify the properties included in the JSON output, while the space parameter can be used to control the indentation of the resulting JSON string.

const obj = {
  name: 'Niva',
  age: 30,
  city: 'Perth'
};

const jsonString = JSON.stringify(obj, null, 2);

console.log(jsonString);

Output

{
  "name": "Niva",
  "age": 30,
  "city": "Perth"
}

In this code, we passed null as the replacer and 2 as the space parameter to JSON.stringify(). This will format the JSON string with 2 spaces of indentation for better readability.

Leave a Comment