Convert JSON containing JS function definition to JavaScript object -


how convert json containing js function definitions

{       "a1": "5",       "b1": "10",       "c1": "function(param1,param2) { return param1 +param2}"   } 

to javascript object containing functions (and not string definition):

{       a1: 5,       b1: 10,       c1: function(param1,param2) { return param1 + param2}   } 

you can pass reviver function json.parse. lets apply custom logic parsed values.

in function can test whether value starts pattern function(...) {:

var obj = json.parse(str, function(k, v) {      if (/^\s*function\s*\([^)]*\)\s*{/.test(v)) {         try {             // using function constructor evaluate function             // definition in global scope             return function('return ' + v)();         }         catch() {             return v; // maybe not js function definition after         }     }     return v; }); 

demo

of course iterate on resulting object , apply same logic after parsing, using reviver function easier if have nested objects/arrays.

note simple test , work anonymous functions. if have named functions, have adjust expression accordingly. basic idea.


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -