Home >Web Front-end >JS Tutorial >How to Convert a JavaScript Object to a Readable String?
How to Display a JavaScript Object in String Format
In JavaScript, it is often necessary to display the content of an object in a readable string format. Similar to the formatted output displayed when a variable is alerted, there are several methods available to achieve this.
SOLUTION 1: Using JSON.stringify()
The native JSON.stringify() method is the most straightforward approach. It converts the object into a JSON string that can be displayed or alerted.
const obj = { name: "John Doe", age: 30 }; const str = JSON.stringify(obj); console.log(str); // Output: {"name":"John Doe","age":30}
To beautify the output with indentation, pass a null value as the second argument.
const str = JSON.stringify(obj, null, 4); // Output: { "name": "John Doe", "age": 30 }
SOLUTION 2: Custom JSON.stringify Replacer (for Circular Structures)
If an object contains circular structures, JSON.stringify() might throw an error. In such cases, a custom replacer function can be used.
const obj = { name: "John Doe", age: 30, children: [ obj // Circular reference ] }; const replacer = (key, value) => { if (value === obj) { return "[Circular]"; } return value; }; const str = JSON.stringify(obj, replacer); console.log(str); // Output: {"name":"John Doe","age":30,"children":["[Circular]"]}
The custom replacer ensures that the circular structure is replaced with a descriptive string to avoid the error.
The above is the detailed content of How to Convert a JavaScript Object to a Readable String?. For more information, please follow other related articles on the PHP Chinese website!