flawopen.com/Insecure Deserialization/JSON.parse() vs eval()
Is JSON.parse() safer than eval()?
Think of the input as a note: JSON.parse() reads fields from a structured form, while eval() hands the note to an interpreter as instructions to carry out. JSON.parse() follows JSON grammar and does not execute JavaScript in the text; the resulting values still need validation before use.
// Do not interpret untrusted data as program source.
const data = eval("(" + untrustedJson + ")");
// Parse JSON as data; invalid JSON throws SyntaxError.
const data = JSON.parse(untrustedJson);
Why this question comes up
Before JSON.parse() was widely available, some JavaScript code used eval() to read JSON because JSON text overlaps with JavaScript expression syntax. That approach evaluates a JavaScript program, so attacker-controlled input can be treated as code rather than constrained to JSON values. Use the JSON parser for JSON.
What JSON.parse() still does not protect
JSON.parse() does not validate business rules, authorize actions, or make parsed strings safe for HTML, SQL, shell commands, or URLs. Validate the expected data shape and use context-appropriate output encoding or parameterized APIs. If you pass a reviver, that application-supplied callback runs during parsing; keep it trusted, simple, and free of side effects based on attacker-controlled values.
FAQ
The JSON text itself is parsed as data, not executed as JavaScript. However, if the application supplies a reviver, that trusted callback is invoked for parsed values and can run code. Do not let attacker-controlled data choose or construct executable callback logic.
No. Check the parsed value against the application’s expected schema and authorization rules. Use output encoding for HTML and parameterized queries for SQL; parsing is not sanitization for those contexts.