Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do I display the content of a JavaScript object in a string format?
To display JavaScript object content as a string, you have several methods. The most common approach is using JSON.stringify() which converts objects into readable JSON format.
Using JSON.stringify()
The JSON.stringify() method converts JavaScript objects into JSON strings:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display JavaScript Object</title>
</head>
<body>
<div id="output"></div>
<script>
// Create a JavaScript object
var person = {
name: "John",
age: 30,
city: "New York",
hobbies: ["reading", "swimming", "coding"]
};
// Convert object to string and display
document.getElementById("output").innerHTML = JSON.stringify(person);
</script>
</body>
</html>
Output
{"name":"John","age":30,"city":"New York","hobbies":["reading","swimming","coding"]}
Formatted JSON Output
For better readability, use the third parameter of JSON.stringify() to add indentation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Formatted Object Display</title>
</head>
<body>
<pre id="formatted-output"></pre>
<script>
var student = {
id: 101,
name: "Alice",
grades: {
math: 95,
english: 88,
science: 92
}
};
// Format with 2-space indentation
document.getElementById("formatted-output").textContent = JSON.stringify(student, null, 2);
</script>
</body>
</html>
Output
{
"id": 101,
"name": "Alice",
"grades": {
"math": 95,
"english": 88,
"science": 92
}
}
Using toString() Method
For simple objects, you can create a custom toString() method:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom toString Method</title>
</head>
<body>
<div id="custom-output"></div>
<script>
var car = {
brand: "Toyota",
model: "Camry",
year: 2022,
toString: function() {
return this.brand + " " + this.model + " (" + this.year + ")";
}
};
document.getElementById("custom-output").innerHTML = car.toString();
</script>
</body>
</html>
Output
Toyota Camry (2022)
Comparison of Methods
| Method | Output Format | Best For |
|---|---|---|
JSON.stringify() |
JSON string | Data serialization, debugging |
JSON.stringify(obj, null, 2) |
Formatted JSON | Pretty printing, readable output |
Custom toString()
|
Custom format | User-friendly display |
Conclusion
JSON.stringify() is the most versatile method for converting JavaScript objects to strings. Use the formatted version with indentation for better readability, or create custom toString() methods for specific display needs.
Advertisements
