To achieve what you need, Jozef's suggestion of using the eval()
function is an option.
However, it's important to note that many sources advise against using eval()
:
- This post discusses why eval() can be considered risky
- When is JavaScript's eval() not evil?
- More insights on the dangers of eval()
- Exploring why using eval() in JavaScript is discouraged
A more secure alternative recommended by this blog () involves utilizing Function instead:
let json = {"foo":"bar","baz":"function(){console.log('I am back working as a function!');}"};
let func = new Function("console.log('I am back working as a function!');");
func();
If modifying the JSON data isn't possible, the str.replace()
method could serve as an alternative.
Cautiously considering the potential risks associated with executing arbitrary code is crucial. It is highly advised to implement whitelisting measures to ensure only predetermined functions are executed. Instead of directly responding with a function, consider following this approach for enhanced security:
function func1() {
console.log('I am back working as a function!');
}
function func2() {
console.log('another code block');
}
let json = {"foo":"bar","baz":"1"};
switch(json.baz) {
case "1": func1();break;
case "2": func2();break;
default: console.error("Invalid response");
}
This guidance aims to provide a safer implementation.