Eval is evil... So what should I use instead?

Solution 1:

json.org has a nice javascript library

simple usage:

JSON.parse('[{"some":"json"}]');
JSON.stringify([{some:'json'}]);

Edit: As pointed out in comments, this uses eval if you look through its source (although it looks to be sanitized first)

to avoid it completely, look at json_parse or json-sans-eval

json2.js is insecure, json_parse.js is slow, json-sans-eval.js is non-validating

Solution 2:

Is there a standard, proven-secure way of doing this?

There is a proposed standard way of doing this, in the forthcoming ECMAScript 3.1 version of JavaScript: JSON.parse.

It will be supported in IE8, Firefox 3.1/3.5 and most likely the other popular browsers in the future. In the meantime, you can fall back to, or use exclusively, eval(). Evil it may or may not be; certainly it will be slower than JSON.parse. But that's the usual way to parse JSON today.

If an attacker is able to inject malcious JavaScript into content you are spitting out via JSON, you have bigger problems to worry about than eval-is-evil.

Solution 3:

I would say, once the input is sanitized, eval is the best way to go. If your server gets compromised, people will be able to send whatever scripts they want to the client anyway. So putting an eval is not a big security risk. If you are worried about people manipulating the packets before they reach the client then, again, the scripts themselves can be modified.

Don't worry about eval. But make sure to wrap it in a try...catch block so your users don't get JS errors if your JSON gets mangled.

:)

Solution 4:

To safely convert JSON to a JS object you should use a JSON parser such as the JSON.parse() function provided by this library.