Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Running a function that is stored in a JSON property

I have a JSON object, like this:

var JSON = 
[
  {
    "cat_function":"(function(){console.log('ITS HAPPENING');})();"
  }
]

JSON[0].cat_function;

From my script, I need to load in the function and execute it. Simply calling JSON[0].cat_function doesn't work, which I kinda expected; what's the best way to get this to run?

To clarify, this JSON data is coming from a CSV and the function is obviously more complex than just a console.log. The function is stored as a string and there's not much that can be done about it.

Any ideas?

like image 995
JVG Avatar asked Nov 19 '25 17:11

JVG


2 Answers

you could do

var functionCode = JSON[0].cat_function;

var value = eval( functionCode );

Anyway, I should warn you that eval is evil so if you can implement another way to import the code it will be better.

like image 116
Edorka Avatar answered Nov 21 '25 08:11

Edorka


This is more a comment/pseudo-code because i currently don't use node.js often (so i could be wrong about it).

But what about doing it in a similar way how jsonp works in the browser:

The response you create (loaded data)

handleResponse({
    status : 200,  /* some statuscode like 200, 400 if required */
    data : {
         cat_function : function(){
                            console.log('ITS HAPPENING');
                        },
        some_data : 12345
    }
});

The function that handles the response (in your application code)

 function handleResponse( response ) {
    response.data.cat_function();
 }

The part where you load and execute it (in your application code)

 vm = require('vm');
 yourResponse = functionToLoadTheResponse();
 vm.runInThisContext(yourResponse);
like image 37
t.niese Avatar answered Nov 21 '25 06:11

t.niese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!