📦 Server Returns JSON String. Parse to Object.
API responses are JSON strings. JSON.parse converts to JavaScript object. Access properties easily.
❌ Without Parse
const response = '{"name":"Alice"}';
console.log(response.name); // undefined
✅ With Parse
const data = JSON.parse(response); console.log(data.name); // 'Alice'
🎯 Fetch + JSON.parse
// Fetch already parses with .json()
fetch('/api/users')
.then(response => response.json())
.then(data => console.log(data));
// Manual parse (XMLHttpRequest)
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.open('GET', '/api/users');
xhr.send();
// Error handling for invalid JSON
try {
const data = JSON.parse(jsonString);
console.log(data);
} catch (error) {
console.error('Invalid JSON:', error);
}
// Reviver function (custom parsing)
const data = JSON.parse(json, (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
💡 Tips
- Always wrap JSON.parse in try/catch (invalid JSON)
- Fetch handles JSON parsing automatically with .json()
- Use reviver for date parsing
- Check response.ok before parsing
“Server returned JSON string, but I forgot to parse. data.name was undefined. Added JSON.parse. Fixed. Essential for API integration.”
