JSON text can be turned into a useful data structure with the
var myData = eval('(' + myJSONText + ')');
eval function has horrendous security
problems, however. Is it safe to use
parse a JSON text? Currently, the best technique for obtaining data from a server in
a web browser is through
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
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 ...