Using JSON Securely

JSON is particularly easy to use in web applications because JSON is JavaScript. A JSON text can be turned into a useful data structure with the eval function:

var myData = eval('(' + myJSONText + ')');

(The concatenation of the parentheses around the JSON text is a workaround for an ambiguity in JavaScript's grammar.)

The eval function has horrendous security problems, however. Is it safe to use eval to parse a JSON text? Currently, the best technique for obtaining data from a server in a web browser is through XMLHttpRequest. XMLHttpRequest can obtain data only from the same server that produced the HTML. eval ing text from that server is no less secure than the original HTML. But, that assumes the server is malicious. What if the server is simply incompetent?

An incompetent server might not do the JSON encoding correctly. If it builds JSON texts by slapping together some strings rather than using a proper JSON encoder, then it could unintentionally send dangerous material. If it acts as a proxy and simply passes JSON text through without determining whether it is well formed, then it could send dangerous material again.

The danger can be avoided by using the JSON.parse method instead of eval (see http://www.JSON.org/json2.js). JSON.parse will throw an exception if the text contains anything dangerous. It is recommended that you always use JSON.parse instead of eval to defend against server incompetence. It is also good practice for the day when the browser provides ...

Get JavaScript: The Good Parts now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.