Using JSON.stringify() with Indentation
In this approach, using JSON.stringify() in JavaScript, specifying optional parameters for indentation to format JSON data into a more readable and structured string representation for debugging or visualization.
Syntax:
const result = JSON.stringify(data, null, 2);
Example: In this example we are using the above-explained approach.
const data = { name: "Aman", age: 21, city: "Noida" };
const result = JSON.stringify(data, null, 2);
console.log(result);
Output
{ "name": "Aman", "age": 21, "city": "Noida" }
How to Convert JSON to string in JavaScript ?
In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission.
There are several methods that can be used to Convert JSON to string in JavaScript, which are listed below:
- Using JSON.stringify() Method
- Using JSON.stringify() with Indentation
- Using JSON.stringify() with Replacer Function
- Using JSON.parse() followed by JSON.stringify() Method
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us