To parse JSON, I believe the best method is to use native JSON support in browsers.
I was looking for a good way to parse JSON in cases where native JSON support is not available.
When i looked at the code in https://github.com/douglascrockford/JSON-js/blob/master/json2.js, what i understood was it first checks whether the data is valid JSON using the regex:
if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) and then applies eval().
jQuery performs $.parseJSON() by 1st using the above regex to check if it's valid JSON and then applies:
return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); if native JSON is available it uses that, otherwise it uses "new Function".
Nowhere else did i find about using function objects for parsing JSON. Which is a better method - using eval() or function object? Can you explain what exactly does (new Function("return " + data))(); perform?
parseJSONis unsafe because it fails to escape characters U+2028 and U+2029, which are line separators in JavaScript but valid raw characters in JSON (a rather poor piece of design).parseJSON('"hello\u2028!"');will fail on browsers without native JSON.json2.jsremembers to escape them in a previous step.