You will need to use the eval() ( doc ) function. Many people have a lot of feelings about this feature. JSON is best suited for transporting data, not functions (see JSON ). Functions must be in the script on the page. There is also a syntax error in your published code (the function is wrapped in single quotes ('), as well as the first parameter to console.log). But...
json = "{\"run\":\"function() { console.log('running...'); }\"}"; //Fixed, thanks obj = JSON.parse(json); eval(obj.run); //Logs "running..."
Update:
Oh, and I was wrong. Eval does not seem to like anonymous functions. With the redesigned code, it will parse json into an object with the run property, which is a String , with the value "function() { console.log('running...'); }" . But when do you eval(obj.run); , you will receive a SyntaxError message about the unexpected (presumably this (in function ( ).
So, I can think of two ways to deal with this:
- Remove the anonymous function in your real JSON string (so make your PHP forget about
function () { ) and evaluate it. This means that it will be called as soon as you eval it. I think you want it to be evaluated by an anonymous function that will be called whenever you want. Thus, you can write a wrapper function (for this you will also need to choose option 1):
function returnEval(str) { return function () { eval(str); } }
This will allow you to call it. So:
obj = JSON.parse(json); obj.run = returnEval(obj.run); obj.run(); //Logs "running..."
Hope this helps!
source share