Beginner Node.js Interview QuestionsBeginnerPractical
Node.js · Question 31
How do you work with JSON in Node.js?
Direct answer
Use JSON.parse for strings and JSON.stringify for objects — read/write JSON files with fs and validate shape before use; handle parse errors and avoid circular references when stringifying.
JSON is the default wire format for REST APIs and config files. Node exposes JSON globally — no import needed — but parsing untrusted input still requires validation.
Why interviewers ask
- API handlers — every POST/PUT body and JSON response path uses parse/stringify.
- Config & content — package.json, interview import JSON, .env is not JSON but often paired with JSON config.
- Failure modes — invalid JSON, BigInt, Date, undefined in objects, circular graphs.
| Method | Use case |
|---|---|
| JSON.parse(str) | String → object; throws SyntaxError on bad input |
| JSON.stringify(obj) | Object → string; replacer/space for pretty print |
| fs + parse | Load local JSON files (content import, fixtures) |
| res.end(JSON.stringify(...)) | Raw http JSON response |
json-handling.mjs
function safeParseJson(raw) {
try {
return { ok: true, data: JSON.parse(raw) };
} catch (err) {
return { ok: false, error: err.message };
}
}
const payload = { topic: "nodejs-interview-questions", count: 30 };
const json = JSON.stringify(payload, null, 2);
// BigInt and undefined are not JSON-safe by default
// JSON.stringify({ n: 1n }) throws