-
-
Save ShaakhDev/719a7e9a6569b5e30ad5e1f202fd4b24 to your computer and use it in GitHub Desktop.
Parse javascript function from json string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (typeof String.prototype.parseFunction != 'function') { | |
String.prototype.parseFunction = function () { | |
var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi; | |
var match = funcReg.exec(this.replace(/\n/g, ' ')); | |
if(match) { | |
return new Function(match[1].split(','), match[2]); | |
} | |
return null; | |
}; | |
} | |
function parseToFunction(t, func) { | |
switch (t?.constructor) { | |
case Object: | |
return Object.fromEntries( | |
Object.entries(t).map(([k,v]) => | |
[k, func([k, parseToFunction(v, func)])] | |
) | |
) | |
case Array: | |
return t.map((v, k) => func([k, parseToFunction(v, func)])) | |
default: | |
return func([null, t]) | |
} | |
} | |
var data = { | |
"processing": true, | |
"serverSide": true, | |
"serverMethod": "post", | |
"ajax": { | |
"url": "data", | |
"cache": false, | |
"callback": "function(arg){console.log(arg)}" | |
}, | |
"others": [ | |
{"anoher_callback": "function(arg){console.log(arg)}"}, | |
{"something": "function(arg){console.log(arg)}"} | |
] | |
}; | |
console.log(parseToFunction(data, ([k,v]) => | |
(typeof v === 'string' && v.slice(0, 8) == "function") ? v.parseFunction() : v | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
parsing js objects literals.