eval( jsonString ) safely for JSON

In general, eval() should only be used to parse JSON if the source of the JSON-formatted text is completely trusted; the execution of untrusted code is obviously dangerous. JSON parsers are available to process JSON input from less trusted sources...[more].

Let's see how it works

<script language="JavaScript">

/* *consider this potentially harmful string **********************************************************************/

var sHarmfulString = "{\"badStuff\":document.getElementById('foo').innerHTML = 'debug = ' + new Date }";

/* *evaluate it, then your client get infected! **********************************************************************/

eval( '(' + sHarmfulString + ')');

/* *Re-define the eval method which escape all DOM ,BOM and JS objects **********************************************************************/

var eval = function(s){ if( typeof(s) === 'string' ) return (Function('var document,top,self,window ,parent,Number,Date,Object,Function,Array,String,Math,RegExp,Image,ActiveXObject; return (' + s + ')'))(); else return null; }

/* * IF the source String is harmful then you'll simply get the error message. **********************************************************************/

try{ eval( '(' + sHarmfulString + ')'); }catch(err){ document.writeln( 'Error:' + (err.message || err) ); } </script>

Example