pass function in json and execute

前端 未结 7 1867
夕颜
夕颜 2020-11-28 07:15

Is there any way that I can pass a function as a json string (conversion with JSON.stringify), send it to another function, parse the json and then execute the function that

相关标签:
7条回答
  • 2020-11-28 07:58

    I've found it helpful to use the JavaScript call() function when working with functions in JSON files.

    var returnData = theJsonData.theFunction.call();
    console.log(returnData); // prints any return data
    

    I hope that helps anyone that stops by!

    0 讨论(0)
  • 2020-11-28 08:07

    Yes, you can. There are tons of ways to do it.

    And there is no need to use the "evil" eval function (please yahoogle why it should be avoided) as pointed out here: http://javascript.about.com/library/bleval.htm

    var tmpFunc = new Function(codeToRun);
    tmpFunc(); 
    

    Whether it was JSON at any stage should be irrelevant.

    0 讨论(0)
  • 2020-11-28 08:08

    Here's a working example

    Basically, you have to be careful with this sort of thing. If you take an extant javascript function, turn it to a string, and eval it, you might run into function redeclaration issues. If you are simply taking a function string from the server and you want to run it, you can do as I did on that jsfiddle:

    Javascript

    var myFunc = "function test() {alert('test');}";
    
    $(document).ready(function() {
        var data = new Object();
        data.func = myFunc;
        var jsonVal = $.toJSON(data);
        var newObj = $.evalJSON(jsonVal);
        eval(newObj.func);
        test();
    });​
    
    0 讨论(0)
  • 2020-11-28 08:14

    take a look at the JSONfn plugin.

    http://www.eslinstructor.net/jsonfn/

    it does exactly what you're asking for.

    -Vadim

    0 讨论(0)
  • 2020-11-28 08:14

    I created a fork of JSONfn which enables you to stringify and parse objects and their prototypes. In my basic tests it worked fine.

    https://github.com/cgarciae/jsonfn

    0 讨论(0)
  • 2020-11-28 08:18

    Yes, you can convert a function to a string with it's toString() method.

    Here's an example to show converting a function to a string and back to a function:

    var myfunc = function () {
        alert('It works!');
    }
    
    var as_string = myfunc.toString();
    
    as_string = as_string.replace('It works', 'It really works');
    
    var as_func = eval('(' + as_string + ')');
    
    as_func();
    
    0 讨论(0)
提交回复
热议问题