Q146: Safe JSON Parsing and Serialization Boundaries
What Interviewers Want To Evaluate
This question checks whether you treat JSON as untrusted runtime data. Interviewers want JSON.parse, JSON.stringify, parse errors, revivers, replacers, data loss, large payload risk, safe boundaries, local storage parsing, and API response validation.
Senior answers should separate transport format from trusted application state.
Short Interview Answer
JSON is a data interchange format, not a type guarantee. JSON.parse can throw, and parsed values should be treated as unknown until validated. JSON.stringify loses unsupported JavaScript values such as undefined, functions, symbols, and BigInt, and it converts dates to strings. Safe JSON handling means catching parse errors, validating shape at boundaries, avoiding sensitive data serialization, and normalizing data before the UI uses it.
Detailed Interview Answer
JSON appears simple because it maps nicely to JavaScript objects.
But JSON supports only:
object
array
string
number
boolean
null
It does not preserve every JavaScript type.
JSON.parse Can Throw
JSON.parse("{ broken json");
This throws a SyntaxError.
Any code parsing external strings should handle failure.
function safeParseJson(value) {
try {
return JSON.parse(value);
} catch {
return null;
}
}
Parsed Data Is Unknown
Parsing JSON does not prove shape.
const raw = JSON.parse(responseText);
The value may be an object, array, string, null, or anything JSON allows.
Validate before relying on fields.
Local Storage Example
Local storage is a common source of broken JSON.
function readPreferences() {
const raw = localStorage.getItem("preferences");
if (!raw) {
return defaultPreferences;
}
const parsed = safeParseJson(raw);
return normalizePreferences(parsed);
}
Users, browser extensions, old app versions, or manual edits can corrupt stored values.
JSON.stringify Data Loss
JSON.stringify({
name: "Asha",
value: undefined,
run() {},
});
undefined and functions do not serialize as normal object fields.
BigInt throws by default.
JSON.stringify({ id: 10n }); // TypeError
Dates Become Strings
const value = JSON.stringify({
createdAt: new Date(),
});
The date becomes a string. Parse and normalize it explicitly on the other side.
Replacer and Reviver
JSON.stringify supports a replacer.
JSON.stringify(value, (key, item) => item);
JSON.parse supports a reviver.
JSON.parse(text, (key, value) => value);
These are useful but can hide conversion behavior. Keep them simple and documented.
Sensitive Data
Be careful what you serialize.
JSON payloads may appear in:
logs
local storage
network traces
analytics
error reports
browser devtools
server logs
Do not stringify tokens, passwords, secrets, or unnecessary personal data.
Large Payloads
Large JSON parsing can block the main thread.
For very large payloads:
paginate
stream if possible
move parsing or processing to a worker
reduce response shape
avoid storing huge JSON in local storage
Performance is part of safe handling.
Common Mistakes
A common mistake is wrapping JSON.parse in try/catch and then trusting the result without validation.
Another mistake is storing long-lived app state in local storage without versioning.
Another mistake is assuming dates survive JSON as Date objects.
Senior Trade-Offs
Parse at the boundary, validate shape, normalize once, and keep internal app state predictable.
Use JSON for transport and persistence, not as a replacement for contracts.
Code or Design Example
function parseJsonObject(value) {
const parsed = safeParseJson(value);
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
return null;
}
return parsed;
}
This gives downstream code a safer starting point.
Debugging Workflow
When JSON handling breaks:
capture raw payload
check parse errors
check value type after parse
check date and BigInt fields
check missing or null fields
check local storage version
validate at boundary
avoid logging sensitive payloads
Interview Framing
Explain that JSON parse gives runtime data, not trusted types. Then discuss parse errors, serialization loss, dates, BigInt, validation, and sensitive data.
Revision Notes
JSON boundaries need parse error handling, validation, normalization, and privacy awareness.
Key Takeaways
Safe JSON handling is about distrust at the edge and confidence inside the app.
Follow-Up Questions
- Can JSON.parse throw?
- What types does JSON support?
- Does JSON preserve Date objects?
- What happens to undefined in JSON.stringify?
- Can BigInt be stringified by default?
- What is a reviver?
- Why validate parsed JSON?
- Why is local storage JSON risky?
- How can large JSON affect performance?
- What should not be serialized?
How I Would Answer This In A Real Interview
I would say JSON parsing is a boundary operation. I would catch parse errors, treat parsed data as unknown, validate and normalize it, and avoid assuming JavaScript types like Date or BigInt survive serialization.