What is the different between eval() and JSON.parse()?
Yeah, guys! I had a question about the eval()
function in an interview in the UK and I always have questioned myself about the difference between the eval()
function and JSON.parse
.
I already used that functions for the same implementation and the solution with both functions works perfectly. My problem to handle the JSON
object as a string comes from a body request HTTP. At that moment it is worked. But, what is safer or not? in which situation I use each one?
eval(string)
So, eval(string)
is a function of JavaScript that takes the string
value and runs like a code, ie it evaluates the expression. In this case, you can evaluate string, boolean, arithmetic, logical, object expression, or statements.
But, this way can I put inject any code? Is not malicious? yes, can be! And some situations such as: inject a JSON
object or even a SQL statement, can vulnerable to possible attacks.
It is happing in the sample below that the price of the book object JSON
was changed before it shows.
Which situation is a good idea to use the eval?
eval()
is used inside another function, how is a global function it is possible to access anytime. For example, JSON.parse
is based on Douglas Crockford's solution, which uses eval()
on line 497.
JSON.parse()
The JSON
implementation is a considering the subset of JavaScript, although it is not! But it is strongly used to together.
The method JSON.parse(string, function?)
is responsible for transform the value string
(first argument in the method) in Object Java Script, Array, string, number, boolean, or null value.
The argument string in JSON.parse
is checked it put in a favorable position to eval
because whether the parse is not working JSON.parse
will throw a SyntaxError
. So, is it safer? yes, it is! the parse implementation has a contract to follow!
Tips:
1). Prefer to use JSON.parse instead of eval in your implementations!
2). Don’t forget to add Validations to your input always!
3). Validations are necessary because in addition to preventing attacks and the experience’s user makes turn better!
References: