【问题标题】:Options to NOT use eval executing JSON string [duplicate]不使用 eval 执行 JSON 字符串的选项 [重复]
【发布时间】:2014-03-09 18:47:55
【问题描述】:

我想看看在不使用 eval() 的情况下,我必须执行哪些选项来执行在 JSON 中查找值的字符串。

我的 JSON 如下所示:

var caso = {
    "_id": "C1M3bqsB92i5SPDu",
    "type": "bpm",
    "bpm": {
        "_data": {
            "_id_bpm": "bpm_solicitud_viaticos"
        },
        "milestones": {
            "solicitud": {
                "toma_de_datos": {
                    "nombre": "RAUL MEDINA",
                    "clave": "123",
                    "departamento": "Finanzas",
                    "cantidad": "456"
                }
            }
        }
    }
}

现在,我有一个带有值的字符串:

var step = "caso.bpm.milestones.solicitud.toma_de_datos.nombre";

我通过这个 JSON 获得了我想要的值:

var thevalue = eval(step);

哪些是我的选项而不是 eval()?既高效又易于实施?

非常感谢您的帮助!

【问题讨论】:

标签: javascript json eval


【解决方案1】:
var pieces = step.split('.'),
    result;

pieces.shift(); //discards superfluous "caso"
result = caso[pieces.shift()];

while (pieces.length >= 1) {
    result = result[pieces.shift()];
}

【讨论】:

    【解决方案2】:

    如果字符串始终采用该格式,则可以拆分并对其进行迭代

    var pieces = step.split('.');
    var parent = window;
    
    while(parent && pieces.length) {
        parent = parent[pieces.shift()];
    }
    
    if(parent && pieces.length === 0) {
        // parent is now the value
    }
    

    这是一个小提琴:http://jsfiddle.net/9ZjEt/

    【讨论】:

    • 可能没有window范围;也可能没有这个:(
    • 我有理由期望 OP 能够解决这个问题。 SO 是帮助人们朝着正确的方向前进,而不是牵着他们的手。
    猜你喜欢
    • 2012-01-04
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2015-09-04
    • 2017-08-26
    • 1970-01-01
    • 2017-05-09
    相关资源
    最近更新 更多