JSON Responses भेजना
APIs आमतौर पर JSON से reply करते हैं, इसलिए आप सही header set करते हैं और अपना data stringify करते हैं।
In this page:
Syntax
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
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. #}
आम गलतियां
- Content-Type भूल जाना
- circular objects भेजना
- 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: