I get that JSON.parse() prevents an attacker from injecting javascript into the response since a JSON parser is just a text parser, not a script parser so please don’t close this is a dup of all the other questions that talk about that. This is a different question.
If an attacker can hijaack your Ajax call and put javascript into the Ajax call aren’t they just as likely to be able to hijack your actual webpage and put arbitrary javascript into your page from which they could accomplish the exact same attack?
Sure, you have nothing to lose by using JSON.parse() instead of eval() (unless you don’t have a JSON parser yet in your environment and have to add more code to get one), but what situations does it really add safety if your web page is being served by the same host as your ajax call?
Yes, it is really safer. Every precaution you do not take is a set of potential exploits you don’t prevent.
An attacker might be able to have some control over your server’s output without being able to change it entirely. Nobody’s suggesting it’s a magic bullet, but it’s potentially faster and you’re not creating a potential vulnerability that could come back and hurt you.
Maybe someone running your server is having a bad day, and does something silly like constructing JSON by concatenating unsanitized user input:
If you’re using
JSON.parse, the worst they can do is shove a large object into your memory. If you’re usingevalthey can hijack everything.