Sub topic 13
Parsing Untrusted JSON Safely
This chapter assumes you already know how JSON.parse works, how to catch its SyntaxError, and how a reviver function visits each key/value pair. Here we apply those tools to JSON that comes from outside your program, such as request bodies, webhooks, query strings, files uploaded by users, or third-party APIs.
What JSON.parse Does and Does Not Protect You From
JSON.parse only reads data. It never runs code, which is why it replaced the old habit of calling eval on JSON text. Never use eval or new Function to read JSON, because they run whatever the input contains.
Being safe to parse does not make the result safe to use. Untrusted JSON brings three main risks:
| Risk | What goes wrong | Defense |
|---|---|---|
| Oversized or deeply nested payloads | Parsing and processing use up memory and CPU | Limit the size before parsing |
| Dangerous keys such as `__proto__` | Later merge or copy code changes `Object.prototype` | Strip or reject those keys |
| Unexpected shape or types | Code assumes `age` is a number and gets a string or an object | Validate, then copy only the fields you expect |
Prototype Pollution Through a Harmless-Looking Key
JSON.parse treats "__proto__" as an ordinary own property. The danger shows up later, when a naive merge function assigns through that key:
const parsed = JSON.parse('{"__proto__": {"isAdmin": true}}');
console.log(Object.keys(parsed)); // ["__proto__"]
console.log({}.isAdmin); // undefined, nothing polluted yet
function naiveMerge(target, source) {
for (const key of Object.keys(source)) {
const value = source[key];
if (typeof value === "object" && value !== null) {
if (typeof target[key] !== "object" || target[key] === null) {
target[key] = {};
}
naiveMerge(target[key], value);
} else {
target[key] = value;
}
}
return target;
}
naiveMerge({}, parsed);
console.log({}.isAdmin); // true, every object now looks like an admin
delete Object.prototype.isAdmin; // clean uptarget["__proto__"] resolves to Object.prototype, so the merge writes isAdmin onto the prototype that every plain object shares.
A Defensive Parsing Pipeline
Handle untrusted input in stages. Each stage rejects a different kind of bad input before the next stage runs.
const BLOCKED_KEYS = new Set(["__proto__", "constructor", "prototype"]);
function parseUntrusted(text, maxLength = 100_000) {
if (typeof text !== "string") throw new TypeError("Expected a string");
if (text.length > maxLength) throw new RangeError("Payload too large");
return JSON.parse(text, (key, value) =>
BLOCKED_KEYS.has(key) ? undefined : value
);
}
function toUser(data) {
if (typeof data !== "object" || data === null || Array.isArray(data)) {
throw new TypeError("Expected an object");
}
if (typeof data.name !== "string" || data.name.length > 100) {
throw new TypeError("Invalid name");
}
if (!Number.isInteger(data.age) || data.age < 0) {
throw new TypeError("Invalid age");
}
return { name: data.name, age: data.age }; // copy only known fields
}
const input = '{"name":"Ada","age":36,"__proto__":{"isAdmin":true},"role":"root"}';
try {
const user = toUser(parseUntrusted(input));
console.log(user); // { name: 'Ada', age: 36 }
} catch (err) {
console.log("Rejected:", err.message);
}The reviver returns undefined for blocked keys, which removes them from the result. toUser builds a new object, so extra fields like role never reach your application.
Common Mistakes
- Validating only that parsing succeeded.
JSON.parse("42"),JSON.parse("null"), andJSON.parse("[]")all succeed. Check that the top-level value is the type you expect. - Spreading the whole parsed object into a database record or a config. Pick your fields explicitly so that the client cannot set
isAdminorid. - Skipping size limits on the server. Set the limit in your body parser (Express's
express.json({ limit })defaults to 100kb) so that huge bodies are rejected before your code reads them. - Writing validators by hand for big schemas. For complex payloads, a schema library such as Zod or Ajv gives you consistent error messages and type checks.
Exercise
An API receives '{"settings":{"_proto_":{"debug":true}}}' and passes the parsed result to a deep-merge helper. Explain why JSON.parse alone did not pollute anything, which step causes the pollution, and two changes that prevent it.
Show answer
JSON.parse creates "_proto" as an ordinary own property on the inner object, so no prototype changes during parsing. The pollution happens when the merge helper assigns through target["proto"], which resolves to Object.prototype, and then writes debug onto it. You can prevent it by stripping "proto_", "constructor", and "prototype" with a reviver (or rejecting them), and by validating the shape and copying only the expected settings fields into a fresh object instead of deep-merging raw input.
Exercise
Why does parseUntrusted check the text length before calling JSON.parse instead of afterward?
Show answer
The cost of parsing comes from the work done while reading the text. If the limit is checked after parsing, a huge payload has already used the memory and CPU, so the check comes too late to protect the server.