JSON Security
Never use eval() to parse JSON — it executes arbitrary code. Use JSON.parse(). Always validate and sanitize JSON from untrusted sources.
Never use eval() to parse JSON — it executes arbitrary code. Use JSON.parse(). Always validate and sanitize JSON from untrusted sources.
// NEVER do this — eval executes any code in the JSON
const data = eval("(" + untrustedJson + ")"); // dangerous!
// Always use JSON.parse
const safe = JSON.parse(untrustedJson);
// Sanitize after parsing
function sanitizeUser(user) {
return {
id: Number(user.id), // Coerce to number
name: String(user.name).slice(0, 100), // Limit length
role: ["user", "admin"].includes(user.role) ? user.role : "user",
};
}
JSON.parse is safe — it cannot execute code. Still validate the resulting data structure before using it.
More in JavaScript