Don't use eval to parse JSON data

Today I read about an interesting security vulnerability in Javascript’s eval() function that I wasn’t aware of previously (which I was naively using to parse JSON data).  Open a developer console and try this:

eval(“alert(‘pwned’)")

The code is executed! This could perhaps be used to return malformed instructions instead of JSON and do something malicious to the client.  However, try this:

JSON.parse(“alert(‘not pwned’)")

Notice that it just throws a parsing error, but of course for actual JSON it still produces the correct object.  Also, here’s a relevant stackoverflow answer.