Skip to content Skip to sidebar Skip to footer

How Do You Do An Eval Within The Scope Of A Json?

I have a json in the form of { a:1, b:10, c:43 } for example. I wish to perform eval( '(a+b-5)*c' ) but applying it to the json, not the place where the json and the formula is. At

Solution 1:

You can use the with keyword, but please don't. Using with and eval is not recommended.

var z = { a:1, b:10, c:43 };
with(z) {
    console.log(eval('a+b'));
}

Here's some more info on MDN.


Solution 2:

Check this out:

function expression (expr) {
    return new Function('obj', 'with (obj) return ' + expr);
}

console.log(expression('(a+b-5)*c')({ a:1, b:10, c:43 }));

Solution 3:

I guess you want something like:

var yourJSon = '{ "a":1, "b":10, "c":43 }'; 
//Your original JSon String (attention to the standard double quotes)

yourJSon = JSON.parse(yourJSon); 
//this will render your JSon string into a "real" object

var answer = eval("(yourJSon.a + yourJSon.b - 5) * yourJSon.c"); 
//And now you can do the eval, using the object's variable to define the scope of that object.

Solution 4:

Dont use eval! USE JSON.parse

JSON.parse

JSON.parse vs. eval()

var obj=JSON.parse(json);

alert((obj.a+obj.b-5)*obj.c)

Post a Comment for "How Do You Do An Eval Within The Scope Of A Json?"