JSON responses
APIs usually reply with JSON, so you set the right header and stringify your data.
In this page:
Syntax
res.json(object);
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(object));
JSON responses
Use res.json in Express or set Content-Type application/json and JSON.stringify manually. Keep a consistent shape such as data and error fields. Dates become ISO strings and undefined values are dropped, while circular structures throw.
Note:
JSON.stringify skips undefined and functions.
Example: JSON responses
const payload = { id: 1, when: new Date(0), skip: undefined, fn() {}, nested: { ok: true } };
console.log(JSON.stringify(payload));
const circular = {}; circular.self = circular;
try { JSON.stringify(circular); } catch (e) { console.log(e.name); }
console.log(JSON.parse('{"a":[1,2,3]}').a.length);
// Output:
// {"id":1,"when":"1970-01-01T00:00:00.000Z","nested":{"ok":true}}
// TypeError
// 3
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting the Content-Type
- Sending circular objects
- Inconsistent response shapes
Chapter Summary
- Set application/json
- JSON.stringify serializes
- undefined is dropped
- Use consistent shapes
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: