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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With