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

JSON Responses भेजना

APIs आमतौर पर JSON से reply करते हैं, इसलिए आप सही header set करते हैं और अपना data stringify करते हैं।

In this page:

  1. JSON Responses
Syntax
javascript
res.json(object);

res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(object));

JSON Responses

Express में res.json इस्तेमाल करें या Content-Type application/json set करें और manually JSON.stringify करें। data और error fields जैसा एक consistent shape रखें। Dates ISO strings बन जाती हैं और undefined values drop होती हैं, जबकि circular structures throw करती हैं।

Note: JSON.stringify undefined और functions skip करता है।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Content-Type भूल जाना
  2. circular objects भेजना
  3. Response shapes को inconsistent रखना
चैप्टर सारांश
  • application/json set करें
  • JSON.stringify serialize करता है
  • undefined drop होता है
  • 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.