4

I have a json string like this:

json = "{'run': 'function() { console.log('running...'); }'}"

How do I run that function inside of the json string?

1
  • eval(json.substring(10, json.length-2))(); ? =) Commented Oct 21, 2010 at 21:49

6 Answers 6

7

You're going to have to use the eval() (doc) function. A lot of people have a lot of feelings about this function. JSON is best for transporting data, not functions (see JSON). The functions ought to lay in the script on the page. Also there's a syntax error in your posted code (function is wrapped in single quotes ('), and so is console.log's first parameter). But...

json = "{\"run\":\"function() { console.log('running...'); }\"}"; //Fixed, thanks
obj = JSON.parse(json);
eval(obj.run); //Logs "running..."

Update:

Oh, and I was mistaken. Eval doesn't seem to like anonymous functions. With the revised code, it will parse json into an object with a run property that is a String, with value "function() { console.log('running...'); }". But when you eval(obj.run);, you will get a SyntaxError declaring an unexpected (. Presumably, this is the ( in function ().

So, I can think of two ways of dealing with this:

  1. Remove the anonymous function in your actual JSON string (so, make your PHP forget about function () {), and eval it. This means it will be called as soon as you eval it.
  2. What I think you want, is to be able to evaluate it to an anonymous function, that will be called when you want. So, you could write a wrapper function (you would need to follow option 1 for this as well):

    function returnEval(str) {
        return function () { eval(str); }
    }
    

    This would allow you to call it. So:

    obj = JSON.parse(json);
    obj.run = returnEval(obj.run);
    obj.run(); //Logs "running..."
    

Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

the second line gave me in Chrome: SyntaxError: Unexpected token ILLEGAL
@weng - Fixed it above. Hope I helped!
0

JSON is not really intended for that, but here seems to be a good example.

1 Comment

CouchDB is using this to store map reduce functions in the database. I have to store functions in the database too.
0

This works for me in Firefox:

var json = "{'run': 'function() { console.log(\\'running...\\'); }'}";
eval('var j = ' + json);
eval('var r = ' + j.run);
r();

Comments

0

Try this, it works:

var JS = { "function" : "alert( new Date().getTime() );" };

new Function ( "", JS["function"] )();

for nested functions you also can use something like this:

jQuery.each( JS, function( method, value ) {
        new Function ( "a, b", "if ( a == 'function' ) { new Function ( '', b )(); }" )( method, value );
} );

Comments

0

I know that thread is old but i want to share with you guys. You can make string a json and parse it easily with these functions.

function makeString(val){
    return JSON.stringify(val, function (key, value) {if (typeof value == 'function') {return value.toString();}return value;});
}

function parseIt(val){
    return JSON.parse(string, function (key, value) {if (value.toString().search("function")>-1) {eval("var func = " + value);return func;}return value;});
}

Comments

0

Without using eval('function()') you could to create a new function using new Function(strName). The below code was tested using FF, Chrome, IE.

<html>
<body>
<button onclick="test()">Try it</button>
</body>
</html>
<script type="text/javascript">
  function test() {

    try {    

        var myJSONObject = {"success" : true, "jsFunc" : "myFunction()"};
        var fnName = myJSONObject.jsFunc;
        var fn = new Function(fnName);
        fn();

      } catch (err) {
        console.log("error:"+err.message);
      }

  }

  function myFunction() {
    console.log('Executing myFunction()');
  }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.