Here’s how to convert a JavaScript object to a JSON string, with detailed explanations and examples:
1. Basic Conversion with JSON.stringify()
The simplest way to convert an object to a JSON string:
const person = {
name: "Alice",
age: 30,
hobbies: ["reading", "gaming"]
};
const jsonString = JSON.stringify(person);
console.log(jsonString);
// Output: {"name":"Alice","age":30,"hobbies":["reading","gaming"]}
2. Advanced Formatting Options
a) Pretty-Printing (Indentation)
Add human-readable formatting with the 3rd parameter:
const jsonPretty = JSON.stringify(person, null, 2);
console.log(jsonPretty);
/* Output:
{
"name": "Alice",
"age": 30,
"hobbies": [
"reading",
"gaming"
]
}
*/
b) Filtering Properties (Replacer Function)
Include/exclude specific properties using the 2nd parameter:
// Only keep "name" and "hobbies"
const filteredJson = JSON.stringify(person, (key, value) => {
return key === "age" ? undefined : value;
}, 2);
c) Whitelist Properties (Array Filter)
Specify which properties to include:
const filteredJson = JSON.stringify(person, ["name", "hobbies"]);
// Output: {"name":"Alice","hobbies":["reading","gaming"]}
3. Handling Special Cases
a) Circular References
Handle objects that reference themselves:
const obj = { a: 1 };
obj.self = obj;
try {
JSON.stringify(obj); // Throws "TypeError: Converting circular structure to JSON"
} catch (err) {
console.log(err.message);
}
Solution: Use a library like flatted
or implement a custom replacer.
b) Dates
Convert Date objects to ISO strings:
const data = { event: "Meeting", date: new Date() };
const json = JSON.stringify(data, (key, value) => {
return value instanceof Date ? value.toISOString() : value;
});
// Output: {"event":"Meeting","date":"2023-09-20T12:00:00.000Z"}
4. Error Handling
Wrap in try-catch for safety:
try {
const json = JSON.stringify(invalidObject);
} catch (err) {
console.error("Stringify failed:", err);
}
5. Common Use Cases
a) API Requests
fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(userData)
});
b) Local Storage
localStorage.setItem("userSettings", JSON.stringify(settings));
6. Key Limitations
- Ignored Values:
undefined
- Functions
- Symbol properties
- Type Conversions:
NaN
→null
Infinity
→null
Date
→ string (ISO format by default)
7. Custom Serialization
Add toJSON()
method to objects:
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
toJSON() {
return {
productName: this.name,
priceUSD: `$${this.price}`
};
}
}
const product = new Product("Laptop", 999);
console.log(JSON.stringify(product));
// Output: {"productName":"Laptop","priceUSD":"$999"}
Summary Table
Feature | Example | Use Case |
---|---|---|
Basic conversion | JSON.stringify(obj) | Simple serialization |
Pretty-printing | JSON.stringify(obj, null, 2) | Debugging/logging |
Property filtering | JSON.stringify(obj, ["id", "name"]) | Partial data export |
Error handling | try-catch block | Production code safety |
Custom serialization | toJSON() method | Specialized object formats |
Browser Compatibility
- Supported in all modern browsers (IE8+ with polyfill)
- Standardized in ECMAScript 5 (ES5)