JSON Security
JSON itself is just text — it can't execute anything. Security problems appear in the code around JSON: how you parse it, what you trust in it, and how you output it. This lesson covers the classic pitfalls and how to avoid them.
1. Never use eval() to parse JSON
Before JSON.parse() existed, code like eval("(" + text + ")") was common. eval runs any JavaScript, so "JSON" from an attacker can do anything your page can:
const fromServer = '{"name": "Lan", "x": (globalThis.hacked = "yes, code ran!")}';
try {
JSON.parse(fromServer);
} catch (err) {
console.log("JSON.parse refused:", err.name);
}
const obj = eval("(" + fromServer + ")"); // DON'T do this
console.log(obj.name, "|", globalThis.hacked);JSON.parse refused: SyntaxError
Lan | yes, code ran!
JSON.parse only accepts data. The same applies to new Function(...) and to JSONP — anything that executes a response is dangerous.
2. Prototype pollution
In JavaScript every object inherits from Object.prototype. If code deep-merges untrusted JSON into an object, a key named __proto__ can modify that shared prototype — and suddenly every object in the program has new properties:
function unsafeMerge(target, source) {
for (const key in source) {
if (typeof source[key] === "object" && source[key] !== null) {
if (typeof target[key] !== "object") target[key] = {};
unsafeMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
const userInput = JSON.parse('{"theme": "dark", "__proto__": {"isAdmin": true}}');
const settings = unsafeMerge({}, userInput);
const someoneElse = {};
console.log(someoneElse.isAdmin); // polluted!
delete Object.prototype.isAdmin; // clean up for the next exampletrue
Why does this work? JSON.parse creates __proto__ as an ordinary own key (harmless so far). But target["__proto__"] in the merge function reads the real prototype, and writing into it changes Object.prototype.
Defences
| Defence | How |
|---|---|
| Skip dangerous keys | Ignore __proto__, constructor, prototype when merging |
| Use prototype-less objects | Object.create(null) has no prototype to pollute |
Use Map for user-keyed data |
Map keys are never confused with properties |
| Validate input | A JSON Schema with additionalProperties: false rejects unknown keys |
| Freeze the prototype | Object.freeze(Object.prototype) (test your app first) |
const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);
function safeMerge(target, source) {
for (const key of Object.keys(source)) {
if (BLOCKED.has(key)) continue;
const value = source[key];
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
if (typeof target[key] !== "object" || target[key] === null) target[key] = {};
safeMerge(target[key], value);
} else {
target[key] = value;
}
}
return target;
}
const userInput = JSON.parse('{"theme": "dark", "__proto__": {"isAdmin": true}}');
const settings = safeMerge({}, userInput);
console.log(settings);
console.log({}.isAdmin);{ theme: 'dark' }
undefined
3. Injection when outputting JSON data
Data from JSON is still untrusted text. Inserting it into other languages without escaping causes injection bugs:
| Destination | Risk | Safe approach |
|---|---|---|
HTML (innerHTML) |
Cross-site scripting (XSS) | textContent, or escape < > & " ' |
| SQL query | SQL injection | Parameterised queries |
| Shell command | Command injection | Pass arguments as an array, never build a string |
Inline <script> in HTML |
</script> in a string ends the script tag |
Escape < as < |
The last one is subtle. Servers often embed initial data in a page as JSON. If a string contains </script>, it breaks out of the script element. Escaping < keeps the JSON identical in meaning but harmless in HTML:
const data = { comment: "</script><script>steal()</script>" };
const naive = JSON.stringify(data);
const safe = JSON.stringify(data).replace(/</g, "\\u003c");
console.log(naive);
console.log(safe);
console.log(JSON.parse(safe).comment === data.comment);{"comment":"</script><script>steal()</script>"}
{"comment":"\u003c/script>\u003cscript>steal()\u003c/script>"}
true
4. Denial of service with huge or deep JSON
A malicious client can send a 2 GB body or an array nested 100,000 levels deep. Parsing it can exhaust memory or the call stack. Servers should:
- Limit the request body size (most frameworks have a setting, e.g. 100 kB–1 MB).
- Reject unexpected nesting depth and array lengths during validation.
- Set timeouts on processing.
const deep = "[".repeat(5000) + "]".repeat(5000);
function depth(value) {
let max = 0;
let stack = [[value, 1]];
while (stack.length) {
const [v, d] = stack.pop();
max = Math.max(max, d);
if (v && typeof v === "object") for (const c of Object.values(v)) stack.push([c, d + 1]);
}
return max;
}
const parsed = JSON.parse(deep);
const d = depth(parsed);
console.log("depth:", d, d > 32 ? "-> rejected" : "-> accepted");depth: 5000 -> rejected
5. Sensitive data in JSON responses
The simplest leak is sending too much. An API that returns the whole user record may include password hashes, internal flags or other people's data. Build responses from an allow-list of fields:
const userRow = { id: 4, name: "Huong", email: "huong@example.com", passwordHash: "$2b$10$abc", isAdmin: false };
const publicJson = JSON.stringify(userRow, ["id", "name"]);
console.log(publicJson);{"id":4,"name":"Huong"}
Checklist
- Parse with
JSON.parse(or your language's JSON library) — nevereval. - Treat every parsed value as untrusted: validate types, ranges and keys.
- Watch for
__proto__when merging or copying objects. - Escape data for its destination (HTML, SQL, shell, script tags).
- Limit body size and nesting depth on servers.
- Send only the fields clients need, with
Content-Type: application/json.
Test yourself
Why is eval() dangerous for parsing JSON?
- It is slower
- It executes any JavaScript contained in the text
- It cannot parse arrays
- It changes key order
Which key is the classic trigger for prototype pollution?
- "prototype_key"
- "__proto__"
- "$ref"
- "__init__"
How do you safely embed JSON inside an HTML <script> tag?
- Base64 it
- Escape
<as\u003c - Remove all quotes
- Use single quotes