1

I created custom stringify method to stringify function as follow

var myStringify=function (obj) {
      return JSON.stringify(obj, function (key, value) {
        if (value instanceof Function || typeof value == 'function') {
          return value.toString();
        }
        return value;
      });
    }

But when I have no idea about parsing string function into function object. Here is my example

var parsed=JSON.parse(jsonString);

After processing JSON.parse function, I got following

parsed.run field has string of function

console.log(parsed.run)  // output is "function(){console.log('foo');}"

I want this function string back into property of parsed object,

{run:"function(){console.log('foo');}"} 

into

{run:function(){console.log('foo');}}

how should I do?

10
  • "function(){console.log('foo');}" is not a valid JSON.. Commented Mar 10, 2016 at 11:07
  • @RayonDabre, I know your point. I posted for short note: complete is parsed={run:"function(){console.log('foo');}"}. Thanks Commented Mar 10, 2016 at 11:08
  • Tell me why would this situation arise ? What you want to achieve ? Commented Mar 10, 2016 at 11:09
  • Have you tried eval()? Commented Mar 10, 2016 at 11:13
  • I want to pass some object to webworker and want to run object function inside webworker. if I can convert function string back to function I can run object function from webworker. Commented Mar 10, 2016 at 11:13

2 Answers 2

1

a regex to match function-strings:

var parseFunctionString = /^\s*function(\s+[a-z0-9$_]*)?\(([^)]*)\)\s*\{([\s\S]*)\}\s*$/i;
//extended regExp, to handle fat-arrow-notation
//var parseFunctionString = /^\s*(?:function(\s+[a-z0-9$_]*)?\(([^)]*)\)\s*\{([\s\S]*)\}|\(([^)]*)\)\s*=>([\s\S]*)|([a-z0-9$_]+)\s*=>([\s\S]*))\s*$/i;

and the usage:

JSON.parse(input, function(k,v){
    var m = typeof v === "string" && v.match(parseFunctionString);
    if(m){
        return Function(m[2], m[3]);
        //if you include the extended regExp
        //return Function(m[2] || m[4] || m[6], m[3] || "return "+( m[5] || m[7] ));

        //return Function("return " + m[0])();
    }
    return v;
})
Sign up to request clarification or add additional context in comments.

Comments

1

Get the body first

var string = parsed.run;
var body = string.substring(string.indexOf("{") + 1, string .lastIndexOf("}"));

Now create a new function object and execute

new Function(body)();

You can try a simple demo on your browser console as

var string = "function(){console.log('foo');}";
var body = string.substring(string.indexOf("{") + 1, string .lastIndexOf("}"));
new Function(body)(); //outputs foo

Refactor this into a function

function convertBodyToFunction(body)
{
   body = string.substring(string.indexOf("{") + 1, string .lastIndexOf("}"));
   return new Function(body);
}
convertBodyToFunction(parsed.run)();

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.