← Back to Node.js Course | Chapter 8: Working with APIs | Lesson 3 of 7

JSON responses

APIs usually reply with JSON, so you set the right header and stringify your data.

In this page:

  1. JSON responses
Syntax
javascript
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

javascript
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
  1. Forgetting the Content-Type
  2. Sending circular objects
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.