Sub topic 13
Parsing Untrusted JSON Safely
This chapter assumes you know the earlier material in this tutorial: how JSON.parse works, how it throws SyntaxError, and how reviver functions visit each key/value pair. You should also be comfortable with prototypes and for...in loops in JavaScript.
Untrusted JSON is any text whose author you do not control. That includes HTTP request bodies, query parameters, WebSocket messages, files uploaded by users, localStorage (other scripts or the user can edit it), and responses from third-party APIs. Parsing this text is safe in itself. The danger comes from what your code assumes about the result and what it does with it next.
Why JSON.parse Is Safer Than the Alternatives
JSON.parse is a pure data parser. It never runs code, never calls getters or constructors, and can only produce plain objects, arrays, strings, numbers, booleans, and null. That is a strong guarantee, and it is why you should never parse JSON any other way.
Before JSON.parse existed, some code used eval to turn JSON-looking text into objects. eval runs any JavaScript it receives, so a payload like the one below would execute:
const payload = '{"a": 1, "b": (function () { console.log("attacker code ran"); return 2; })()}';
// Never do this: eval executes the embedded function.
// const data = eval("(" + payload + ")");
try {
JSON.parse(payload);
} catch (err) {
console.log(err instanceof SyntaxError); // true: JSON has no functions
}The same rule applies to new Function(...), setTimeout with a string argument, and template engines that evaluate expressions. If the input is supposed to be JSON, JSON.parse is the only parser you need.
The Threat Model in Practice
Once the text parses, the attacker controls the shape of the result. Most real bugs come from one of the risks in this table.
| Risk | What goes wrong | Mitigation |
|---|---|---|
| Unexpected type | Code expects an object and gets `null`, a number, or an array | Check the top-level type before reading fields |
| Missing or wrongly typed fields | `data.items.length` throws, or `"5"` is treated as a number | Validate every field you use |
| Extra fields | Fields like `isAdmin: true` get copied into records | Build a new object from an allowlist of fields |
| Prototype pollution | A `__proto__` key gets merged into `Object.prototype` | Skip dangerous keys and use safe merging |
| Oversized input | Huge payloads use up memory and CPU | Limit size before parsing |
| Information leaks | Error messages or logs echo secrets or internals | Return generic errors and log carefully |
| Unsafe revivers | A `"type"` field picks which class to construct | Map type names through a fixed registry |
Valid JSON, wrong shape
All of the following are valid JSON, and JSON.parse accepts every one:
const inputs = ["null", "42", '"hello"', "[]", "true", '{"user": null}'];
for (const text of inputs) {
const value = JSON.parse(text);
const kind = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
console.log(text, "->", kind);
}
// null -> null
// 42 -> number
// "hello" -> string
// [] -> array
// true -> boolean
// {"user": null} -> objectCode like JSON.parse(body).user.name will throw a TypeError for most of these inputs, and that crash may take down a request handler or a worker. A successful parse tells you only that the text was syntactically valid. It says nothing about the shape.
Prototype Pollution
Prototype pollution is an attack where input data ends up adding or changing properties on Object.prototype, so that every object in the program inherits them.
JSON.parse on its own handles the key "__proto__" correctly. It creates an ordinary own property named "__proto__" and does not change the prototype of the result:
const parsed = JSON.parse('{"__proto__": {"isAdmin": true}}');
console.log(Object.keys(parsed)); // [ '__proto__' ]
console.log(parsed.isAdmin); // undefined
console.log(Object.getPrototypeOf(parsed) === Object.prototype); // trueThe trouble starts when that object goes through a naive deep merge, a common pattern for applying user settings on top of defaults. In the merge, target["__proto__"] is an assignment target, and assigning through it reaches the real prototype:
function naiveMerge(target, source) {
for (const key in source) {
const value = source[key];
if (typeof value === "object" && value !== null) {
target[key] = naiveMerge(target[key] || {}, value);
} else {
target[key] = value;
}
}
return target;
}
const settings = {};
naiveMerge(settings, JSON.parse('{"__proto__": {"isAdmin": true}}'));
const unrelated = {};
console.log(unrelated.isAdmin); // true: every object is now "admin"
delete Object.prototype.isAdmin; // clean up the pollution
console.log(unrelated.isAdmin); // undefinedHere target["__proto__"] evaluates to Object.prototype. The recursive call then writes isAdmin onto it. Any later check such as if (user.isAdmin) passes for every object that lacks its own isAdmin property.
Defenses
You can stop this at several layers, and using more than one is reasonable.
- Strip dangerous keys during parsing with a reviver. If a reviver returns
undefined, that property is deleted. - Write merge functions that skip dangerous keys and copy only own properties.
- Use objects with no prototype (
Object.create(null)) or aMapfor dictionaries keyed by user input.
const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype"]);
function stripDangerousKeys(key, value) {
return DANGEROUS_KEYS.has(key) ? undefined : value;
}
function safeMerge(target, source) {
for (const key of Object.keys(source)) {
if (DANGEROUS_KEYS.has(key)) continue;
const value = source[key];
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
const existing = Object.hasOwn(target, key) ? target[key] : {};
target[key] = safeMerge(existing, value);
} else {
target[key] = value;
}
}
return target;
}
const cleaned = JSON.parse('{"theme": "dark", "__proto__": {"isAdmin": true}}', stripDangerousKeys);
console.log(cleaned); // { theme: 'dark' }
const merged = safeMerge({}, JSON.parse('{"__proto__": {"isAdmin": true}}'));
console.log({}.isAdmin, merged); // undefined {}Object.keys returns only own enumerable properties, so the merge never walks inherited properties. Object.hasOwn stops the merge from reading an inherited value as its starting point. Libraries such as lodash have shipped fixes for this exact bug, so keep merge and "set by path" utilities up to date.
Validate, Then Build Your Own Object
The most effective defense is to validate the parsed value and then copy only the fields you expect into a fresh object. That one step handles wrong types, missing fields, extra fields, and most pollution risks.
The diagram below shows the full pipeline for a request body.
Here is a complete implementation for a small order payload:
const MAX_LENGTH = 10_000;
const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype"]);
class ValidationError extends Error {}
function parseOrder(text) {
if (typeof text !== "string" || text.length > MAX_LENGTH) {
throw new ValidationError("Payload missing or too large");
}
let data;
try {
data = JSON.parse(text, (key, value) =>
DANGEROUS_KEYS.has(key) ? undefined : value
);
} catch (err) {
if (err instanceof SyntaxError) {
throw new ValidationError("Body is not valid JSON", { cause: err });
}
throw err;
}
if (data === null || typeof data !== "object" || Array.isArray(data)) {
throw new ValidationError("Expected a JSON object");
}
const { productId, quantity, note } = data;
if (!Number.isSafeInteger(productId) || productId <= 0) {
throw new ValidationError("productId must be a positive integer");
}
if (!Number.isInteger(quantity) || quantity < 1 || quantity > 100) {
throw new ValidationError("quantity must be an integer from 1 to 100");
}
if (note !== undefined && (typeof note !== "string" || note.length > 500)) {
throw new ValidationError("note must be a string of at most 500 characters");
}
// Build a fresh object: extra fields such as "price" or "isAdmin" are dropped.
return { productId, quantity, note: note ?? "" };
}
const attempts = [
'{"productId": 12, "quantity": 2, "price": 0, "isAdmin": true}',
'{"productId": "12", "quantity": 2}',
"null",
"{bad json}",
];
for (const text of attempts) {
try {
console.log("OK:", parseOrder(text));
} catch (err) {
if (!(err instanceof ValidationError)) throw err;
console.log("Rejected:", err.message);
}
}
// OK: { productId: 12, quantity: 2, note: '' }
// Rejected: productId must be a positive integer
// Rejected: Expected a JSON object
// Rejected: Body is not valid JSONSeveral details matter here:
Number.isSafeIntegerrejectsNaN, strings, fractions, and integers too large to hold exactly. The last case links back to the precision limits covered earlier: an ID like9007199254740993cannot be represented as aNumber, and accepting it would silently store a different ID.- The client chose
priceandisAdmin, and both are thrown away. Never pass parsed input straight to a database insert or an object spread like{ ...defaults, ...data }unless you have validated every key. - A custom error class separates expected rejections from real bugs, the same way
safeParsechecked forSyntaxErrorearlier in the tutorial.
For larger payloads, writing validators by hand gets tedious. Schema libraries such as Ajv (JSON Schema) or Zod describe the shape declaratively and give the same allowlist behavior when configured to strip unknown keys.
Limiting Resource Use
JSON.parse is fast, but it runs synchronously and keeps the whole result in memory. A 500 MB body blocks the event loop while it parses and can exhaust the heap. Deeply nested input such as [[[[...]]]] can also be expensive, both to parse and for any recursive code that walks the result afterwards, such as a merge or a validator.
Practical limits:
- Cap the body size at the transport layer (server config, reverse proxy, or framework option).
- Cap array lengths and string lengths during validation, as
parseOrderdoes fornote. - If your own code recurses over parsed data, add a depth limit and reject input beyond it.
function maxDepth(value, depth = 0, limit = 32) {
if (depth > limit) throw new RangeError("JSON nested too deeply");
if (value !== null && typeof value === "object") {
for (const child of Object.values(value)) maxDepth(child, depth + 1, limit);
}
return depth;
}
const deep = JSON.parse("[".repeat(50) + "]".repeat(50));
try {
maxDepth(deep);
} catch (err) {
console.log(err.message); // JSON nested too deeply
}Revivers That Construct Types
The reviver chapter showed how to turn ISO strings back into Date objects. A tempting extension is a generic reviver that reads a "type" field and constructs whatever class it names, for example new globalThis[value.type](...). That lets an attacker pick which constructor runs, and with which arguments. Use a fixed registry instead:
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
const REVIVERS = {
point: (v) =>
Number.isFinite(v.x) && Number.isFinite(v.y) ? new Point(v.x, v.y) : v,
};
function typedReviver(key, value) {
if (value && typeof value === "object" && Object.hasOwn(REVIVERS, value.type)) {
return REVIVERS[value.type](value);
}
return value;
}
const shape = JSON.parse('{"a": {"type": "point", "x": 1, "y": 2}, "b": {"type": "Function"}}', typedReviver);
console.log(shape.a instanceof Point); // true
console.log(shape.b); // { type: 'Function' } left as plain dataObject.hasOwn(REVIVERS, ...) matters. A plain lookup like REVIVERS[value.type] with type: "constructor" would find the inherited Object.prototype.constructor and call it.
Errors and Logging
When parsing fails, tell the client that the body was invalid. Do not echo the engine's SyntaxError message, the raw body, or a stack trace. Those messages differ between engines and can reveal internals. When you log, remember that request bodies often contain passwords or tokens. Log a length or a hash instead of the text, or redact fields with a replacer as shown in the replacer chapter.
Exercise
A handler runs const prefs = Object.assign({}, defaults, JSON.parse(body)); and then if (prefs.isAdmin) grantAccess();. JSON.parse does not pollute prototypes, so is this code safe? Explain what goes wrong and how to fix it.
Show answer
It does not pollute Object.prototype, because Object.assign is a shallow copy and the "_proto_" key at most changes the prototype of the single new prefs object. It is still unsafe: the client can send {"isAdmin": true}, and the spread copies that field straight into prefs. The fix is to validate the parsed object and copy only the allowlisted preference fields (for example theme and language) into a new object, never trusting authorization flags from input.
Exercise
Why does safeMerge use Object.hasOwn(target, key) ? target[key] : {} rather than target[key] || {}?
Show answer
target[key] also reads inherited properties. For a key like "toString", or any key polluted onto the prototype by other code, the merge would start from an inherited object or function and might write into shared prototype state. Object.hasOwn makes sure the merge only reuses objects that actually belong to the target.
Exercise
parseOrder('{"productId": 9007199254740993, "quantity": 1}') throws "productId must be a positive integer". Why, given that the number in the text is a positive integer?
Show answer
JSON.parse converts the number to a double, which cannot hold 9007199254740993 exactly and rounds it to 9007199254740992. That value is above Number.MAXSAFEINTEGER, so Number.isSafeInteger returns false. The rejection is correct: accepting the value would silently use a different ID. If IDs this large are legitimate, the API should send them as strings and the server should validate them as strings or convert them to BigInt.