Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble understanding jQuery.parseJSON JSON.parse fallback

This is the source of $.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 have trouble understanding the following fallbacks

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

and also ( this one is not in jQuery )

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

I would like to know these things

  1. How this parsing fallback works really?
  2. Why eval is not used in the fallback? (Is it not faster than new Function())
like image 318
naveen Avatar asked Oct 11 '22 07:10

naveen


1 Answers

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

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

As far as performance, some quick googling found claims that new Function() is faster than eval, though I have not tested this myself.

like image 62
James Montagne Avatar answered Oct 18 '22 00:10

James Montagne