I have a string like this:
var jsontext = 'function(prog) {return ' + path + ';}';
and i want to parse this into javascript.
How can i do this?
Thomas
I have a string like this:
var jsontext = 'function(prog) {return ' + path + ';}';
and i want to parse this into javascript.
How can i do this?
Thomas
This is not JSON, but Javascript as a text string that you want to evaluate.
You will want to use the eval(jsontext)
function, but I would highly discourage this as it is a very risky function as it executes the script with the privileges of the caller. It is also a bad idea for performance reasons. If at all possible, define your function in the script itself instead of as a string!
See here.
Here the complete code. The eval function doesn't work and i need a workaround.
function buildRecursiveFilter(filterDef) { var filterFuncs = [];
// Rekursiv für alle nodes Regex filter funktionen definieren
naw.visitNode(filterDef, function(node, path) {
if (typeof node !== "object") {
var selector = eval("(function(TBM) { return " + path.toUpperCase() + "; })") ;
var tester = buildRegexFilter(node, selector);
filterFuncs.push(tester);
}
}, "tbm");
if (filterFuncs.length === 0) return noFilter;
// wende alle test funktionen auf tbm an und liefere die UND Verknüpfung
return function(tbm) {
return _.reduce(
_.map(filterFuncs, function(f) { return f(tbm); }),
function(akku, res) { return akku && res; });
};
}
function buildRegexFilter(filterDef, fieldSelector) {
fieldSelector = fieldSelector || (function(tbm) { return tbm.WP; });
var def = filterDef;
if (typeof (def) === 'string') {
def = def.split(',');
}
var filters = [].concat(def); // Array erzwingen
filters = _.map(filters, function(s) { return $.trim(s); });
var expression = '(' + filters.join('|') + ')';
var rx = expression !== '(.*)' ? new RegExp(expression) : undefined;
return function (tbm) {
return rx.test(fieldSelector(tbm));
};
}
Thomas
I've found a solution for my problem. I have removed the line with eval and have it replaced with this:
var fn = "function(tbm) { return " + path.toUpperCase() + "; }";
var selector = new Function("return (" + fn + ")")();
Thomas