How can I convert an object to a JSON string in JavaScript with indentation?
Ava W
ava w profile pic

In JavaScript, you can convert an object to a JSON string with indentation by using theJSON.stringify() method with additional parameters. Here's an example of how you can achieve this:

1
2
3

const obj = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(obj, null, 2);

In this example,obj is the object that you want to convert to a JSON string, andnull represents the replacer function or an array of properties to include in the string. The third parameter,2, is the indentation level. TheJSON.stringify() method converts the object to a JSON string representation. By specifying2 as the third parameter, you indicate that you want the string to be indented with two spaces for each level. The resultingjsonString will be:

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

The properties are displayed on separate lines with an indentation of two spaces. If you want to use a different indentation character or a different number of spaces, you can pass a string as the third parameter instead. For example, if you want to use four spaces for indentation:

1
2

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

This will produce the same result as before, but with four spaces for each level of indentation. Note that the resulting JSON string with indentation is primarily useful for human-readable display or formatting. When transmitting or storing JSON data, the actual string does not contain the indentation.