How can I convert a JavaScript object to a JSON string with custom indentation?Gable E
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.
Similar Questions
How can I convert an object to a JSON string in JavaScript with 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 do I convert an object to a JSON string in JavaScript?
How can I convert a JavaScript array to a string with a custom separator?
How can I convert an object to a string in JavaScript?
How can I convert a string to an object in JavaScript?
How can I convert a string to a date object in JavaScript?
How do I convert an object to an JSON string in JavaScript?
How can I convert a string to a nested object in JavaScript?
How can I convert a JavaScript string to an object by parsing JSON?
How can I convert a JavaScript array to a CSV string with custom column headers?
How can I convert an object to an XML string in JavaScript?
How can I convert a JavaScript string to a Blob object?
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 an object to a query string in JavaScript?
How can I convert an object to a query string in JavaScript?