Last active
July 10, 2023 20:24
-
-
Save yetimdasturchi/6d3502f166cac0b771c6741b89568c9c 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 | |
)) |
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
var myobj = { | |
"sayhello": function (name) { | |
console.log(name); | |
} | |
}; | |
var functions = []; | |
var result = JSON.stringify(myobj, function (key, val) { | |
if (typeof val === 'function') { | |
functions.push(val.toString()); | |
return "{func_" + (functions.length - 1) + "}"; | |
} | |
return val; | |
}).replace(/"\{func_(\d+)\}"/g, function (match, id) { | |
return '"'+functions[id]+'"'; | |
}); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment