Handling Invalid JSON β Interview Questions
β‘ Short Answer
Never assume input is valid: wrap parsing in try/catch (or a safeParse helper that returns a result/null), verify HTTP status and Content-Type first, and after parsing validate the shape (required fields/types) before use. On failure, log the raw payload and return a clear error (e.g. 400) rather than letting the parser throw uncaught.
βCoffee Chat Question
Concept Made Simple
βHow do you handle invalid or malformed JSON?β
π§ Mind Map Answer
Remember It Faster
β¨οΈHands-on Keyboard
Learn by Doing
function safeParse(text) {
try {
return { ok: true, data: JSON.parse(text) };
} catch (e) {
return { ok: false, error: e.message };
}
}
const r = safeParse('{bad json');
console.log(r.ok ? r.data : "Invalid JSON: " + r.error);Invalid JSON: Unexpected token b ...
π₯What If?
Think Beyond the Expected
Should a public API crash or return a 500 when it receives malformed JSON?
Neither β return 400 Bad Request with a clear message. Malformed input is a client error, not a server fault, so a 500 is misleading and an uncaught throw can take down the request handler. Parse defensively, and respond with 400 plus enough detail for the caller to fix their payload.
πReal World
Robust services treat every inbound body as hostile: guard, safe-parse, validate, and respond with a precise 400. This is also a security posture β malformed or oversized JSON is a common probing technique.
π―Interviewer's Expectation
Keywords they're listening for:
β οΈCommon Mistakes
- βLetting JSON.parse throw uncaught
- βReturning 500 for a client's bad JSON
- βSkipping shape validation after a successful parse
β Best Practices
- βSafe-parse + validate at every boundary
- βReturn 400 with actionable messages
- βCap request body size
πFollow-up Questions
- 1Why is malformed input a 400 and not a 500?
- 2How does JSON Schema fit into validation?
- 3How do you guard against oversized payloads?
π§©Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Parsing (JSON) Interview question: "How do you handle invalid or malformed JSON?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
β Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission β at no extra cost to you. It helps keep Full Stack Interview Guru free.