I'm trying to write a recursive function that, if it contains "expr" as a key instead of "number" it will feed that section of the JSON back into the function. My code is the following:
var result = 0;
function calc(str) {
var obj = JSON.parse(str);
if(obj.hasOwnProperty("expr")) {
var temp = obj.expr;
JSON.stringify(temp);
calc(temp);
}
if (obj.op == "add") {
var i = parseInt(obj.number);
result += i;
} else if(obj.op == "subtract") {
var i = parseInt(obj.number);
result -= i;
}
return result;
}
I'm getting a Syntax Error saying "Unexpected token o in JSON at position 1." Does Stringify not reformat it back into a string? If so, how would I go about that?
My input is something like the following:
result = calc('{"op" : "add", "number" : 5}');
result = calc('{"op" : "subtract", "number" : 2}');
result = calc('{"op" : "add", "number" : 19}');
result = calc('{"op": "subtract", "expr" : {"op" : "add", "number" : 15}}');
JSON.stringifyreturns a string, it doesn't modify its argument. The mistake is the line abovecalc(temp)JSON.stringify()can modify the argument passed to return a different result than argument as a string