How can I convert an object to a JSON string in JavaScript with indentation?Ava W
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.
Similar Questions
How can I convert a JavaScript object to a JSON string with custom indentation?
How can I convert a JSON string to an object in JavaScript?
How can I convert a JSON string to an object in JavaScript?
How can I convert an object to a string in JavaScript?
How do I convert an object to a JSON string in JavaScript?
How do I convert an object to an JSON string in JavaScript?
How can I convert a string to an object in JavaScript?
How can I convert an object to an XML string in JavaScript?
How can I convert an object to a query string in JavaScript?
How can I convert an object to a query string in JavaScript?
How can I convert an object to a JSON file in JavaScript?
How can I convert a JavaScript string to an object by parsing JSON?
How can I convert an array to a JSON string in JavaScript?
How can I convert a string to a date object in JavaScript?
How can I convert a function to a string in JavaScript?
How can I convert a function to a string in JavaScript?
How can I convert a string to a nested object in JavaScript?
How can I convert an object to a set in JavaScript?