📦 Objects Don’t Travel Well. Strings Do.
Can’t send objects directly. JSON.stringify converts objects to JSON strings. Send to server, parse back with JSON.parse.
❌ Sending Object (Won’t Work)
const user = { name: 'Alice', age: 30 };
fetch('/api/users', {
method: 'POST',
body: user // ❌ Object won't send correctly
});
✅ JSON.stringify
const user = { name: 'Alice', age: 30 };
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user) // ✅ JSON string
});
🎯 Advanced Stringify
// With replacer (filter properties)
const json = JSON.stringify(user, ['name', 'email']);
// Pretty print (indentation)
const pretty = JSON.stringify(user, null, 2);
// With reviver (parse)
const obj = JSON.parse(json, (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
// Handle circular references
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]';
seen.add(value);
}
return value;
};
};
const safeJson = JSON.stringify(circularObj, getCircularReplacer());
💡 Tips
- Always set Content-Type: application/json header
- Use JSON.parse() for server response
- Handle JSON.parse errors (try/catch)
- Don’t stringify functions (they’ll be dropped)
“Tried to send object directly, server got [object Object]. Used JSON.stringify. Server parsed correctly. JSON is the universal data format.”
