How can I convert a JavaScript object to a JSON string with custom indentation?
Gable E
gable e profile pic

To convert a JavaScript object to a JSON string with custom indentation, you can use theJSON.stringify() method with the additional parametersreplacer andspace. Thereplacer parameter allows you to specify a function that can modify the serialization process by transforming the values or omitting certain properties from the final JSON string. However, for the purpose of custom indentation, we can leave it asnull. Thespace parameter is used to control the indentation and whitespace formatting in the resulting JSON string. You can provide either a number or a string as the value ofspace to control the indentation level. If you provide a number, it represents the number of spaces to be used for indentation. If you provide a string, that string will be repeated for each indentation level. Here's an example that demonstrates how to convert an object to a JSON string with custom indentation:

1
2
3
4
5
6
7
8
9
10

const data = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const jsonString = JSON.stringify(data, null, 2); // 2 spaces for indentation

console.log(jsonString);

Output:

json { "name": "John", "age": 30, "city": "New York" }

In the above example, theJSON.stringify() method is used to convert thedata object to a JSON string. The second parameter,replacer, is set tonull since we don't need to modify the serialization process. The third parameter,space, is set to2 to specify that we want the JSON string to be indented with 2 spaces. By adjusting the value ofspace, you can control the indentation level according to your preference. Note that thespace parameter is optional. If you omit it or passnull, the resulting JSON string will be compact without any indentation or whitespace.