Troubleshooting jQuery.parseJSON JSON.parse fallback

This is the source$.parseJSON

function (data) {
    if (typeof data !== "string" || !data) {
        return null;
    }

    // Make sure leading/trailing whitespace is removed (IE can't handle it)
    data = jQuery.trim(data);

    // Attempt to parse using the native JSON parser first
    if (window.JSON && window.JSON.parse) {
        return window.JSON.parse(data);
    }

    // Make sure the incoming data is actual JSON
    // Logic borrowed from http://json.org/json2.js
    if (rvalidchars.test(data.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, ""))) {

        return (new Function("return " + data))();

    }
    jQuery.error("Invalid JSON: " + data);
}

I find it difficult to understand the following backups

return (new Function("return " + data))();

as well (this one is not in jQuery)

return (eval('('+ data + ')')

I would like to know these things

  • How does this debugging effect really work?
  • Why is eval not used in reserve? (This is not faster than new Function())
+5
source share
1 answer

new Function() allows you to pass your function as a string.

In this case, a function is created to simply return the object described in the json string. Since json is a valid object literal, this function simply returns the object defined in json. A new function is immediately called, returning this object.

, new Function() , eval, .

+4

All Articles