递归JSON字符串解析器

时间:2018-10-19 05:44:23

标签: javascript json recursion

我在解析JSON字符串时需要帮助,无法完全解决问题所在。

value = 0;

function calc(string) {
    let x = JSON.parse(string);
    var y;


    if (x.expr != undefined){
         y = JSON.stringify(x.expr);
    }
    else {
         y = x;
    }
    if (y.op == 'add') {
        return value = value + y.number;
    }
    else if (y.op == 'subtract') {
        return value = value - y.number;
    }
    x.expr = y;
    calc(y);

};

//console.log(calc('{"op" : "add", "number" : 5}' )); //expected value 5
//console.log(calc('{"op" : "subtract", "number" : 2}' )); //expected value 3
//console.log(calc('{"op" : "add", "number" : 19}' )); //expected value 22
console.log(calc('{"op": "subtract", "expr" : {"op" : "add", "number" : 15}}' )); //expected value 0
//console.log(calc('{"op": "add", "expr" : {"op" : "add", "expr" : {"op" : "subtract", "number" : 3}}}' )); //expected value 0

我没有注释我要调试的部分。我对递归不太满意,我正在尝试读取JSON字符串以计算数字。

嵌入式表达式对我来说是新事物,所以我不确定该如何进行,即基本情况是什么?

请帮助我!

1 个答案:

答案 0 :(得分:0)

JSON.parse reviver parameter可用于遍历reverse level order中的所有值:

var value = 0;

function calc(string) {
    var number;

    JSON.parse(string, function(key, val) {
        if (val.op) { 
            if ('number' in val)
                number = val.number;

            if (val.op === 'add')
                console.log(value, '+', number, '=', value += number, '\t', JSON.stringify(val));
            else
                console.log(value, '-', number, '=', value -= number, '\t', JSON.stringify(val));
        }
        return val;
    });
};

calc( '{"op": "subtract", "expr" : {"op" : "add", "number" : 15}}' );
calc( '{"op": "add", "expr" : {"op" : "add", "expr" : {"op" : "subtract", "number" : 3}}}' );