SyntaxStudy
Sign Up
JavaScript JSON Security Considerations
JavaScript Intermediate 5 min read

JSON Security Considerations

JSON Security

Never use eval() to parse JSON — it executes arbitrary code. Use JSON.parse(). Always validate and sanitize JSON from untrusted sources.

Example
// 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",
  };
}
Pro Tip

JSON.parse is safe — it cannot execute code. Still validate the resulting data structure before using it.