Parse JSON using JSON Parser or eval()!

JSON is in use for data interchange format. It is accepted in many programming language whether client side or server side language. So, learning JSON and using it securely is needed.
Both JavaScript and PHP has in-built functions for this.
JSON parser function is useful if your JSON text is coming from external source for security of your website. This parseJSON() is basically from Douglas Crockford JSON library. Using the below function, I want to show you why JSON parse is needed instead of just eval() for parsing JSON object.

<script type="text/javascript">
String.parseJSON  = (function (s) {
  var m = {
    'b': '\b',
    't': '\t',
    'n': '\n',
    'f': '\f',
    'r': '\r',
    '"' : '\"',
    '\': '\\'
  };
  s.parseJSON = function (filter) {
     /*
           Reason: Why this function is useful?
     */
    // Parsing happens in three stages. In the first stage, we run the text against
    // a regular expression which looks for non-JSON characters. We are especially
    // concerned with '()' and 'new' because they can cause invocation, and '='
    // because it can cause mutation. But just to be safe, we will reject all
    // unexpected characters.
    try {
      if (/^("(\.|[^"\nr])*?"|[,:{}[]0-9.-+Eaeflnr-u nrt])+?$/.test(this)) {
          // In the second stage we use the eval function to compile the text into a
          // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
          // in JavaScript: it can begin a block or an object literal. We wrap the text
          // in parens to eliminate the ambiguity.
          var j = eval('(' + this + ')');
          // In the optional third stage, we recursively walk the new structure, passing
          // each name/value pair to a filter function for possible transformation.
          if (typeof filter === 'function') {
            function walk(k, v) {
              if (v && typeof v === 'object') {
                for (var i in v) {
                  if (v.hasOwnProperty(i)) {
                    v[i] = walk(i, v[i]);
                  }
                }
              }
              return filter(k, v);
            }
            j = walk('', j);
          }
          return j;
        }
      } catch (e) {
  // Fall through if the regexp test fails.
      }
      throw new SyntaxError("parseJSON: filter failed");
    };
  }
) (String.prototype);
// End public domain parseJSON block
function SyntaxError(e)
{
 alert(e);
}
</script>

Now check these line and their output:

<script type="text/javascript">
JSONData = '{"color" : new Date()}';
document.writeln(eval('('+JSONData + ')').color);
// and
testObject = JSONData.parseJSON();
document.writeln(testObject.color);
</script>
So, for security reason using JSON parser is good.