I am writing a script where I need to parse JSON in browsers that don’t support JSON.parse(). I have strict size objectives (total size < 20 kb) so I cannot rely on an external library like jQuery.
The usual approach would be to use eval() but I am concerned that it is not safe, as I have no control on the JSON strings (provided by an external source).
I came up with the idea to use a script tag to create my object:
var json='{"name":"Me","age":"30"}';
var scr=document.createElement("script");
scr.innerHTML="var obj="+json;
document.body.appendChild(scr);
This seems to work, as demonstrated here:
http://jsfiddle.net/bz8f7/
Am I missing something here? Are there cases where my method won’t work, or won’t be safe?
Note: I am aware that this method creates a global variable, and I am fine with that for my use case.
You are still evaluating JavaScript, just by using a more complex, less efficient method than
eval. It has all the safety issues of eval.