【问题标题】:nodejs json dynamic propertynodejs json动态属性
【发布时间】:2012-11-02 09:55:12
【问题描述】:

我想制作一个接收 json 对象和路径的简单应用程序。结果就是那个路径的值,例如:

node {"asd":{"qwe":"123", "ert":"465"}} asd.qwe

应该回我:123

我正在使用这个:

var result = JSON.parse(jsonToBeParsed);
console.log(result["asd"]["qwe"]);

但我希望能够通过字符串动态地获取值。 有没有办法做这样的事情? :

var result = JSON.parse(jsonToBeParsed);
var path = "asd.qwe" //or whatever
console.log(result[path]);

【问题讨论】:

    标签: json node.js parsing


    【解决方案1】:
    var current = result,
        path = 'asd.qwe';
    
    path.split('.').forEach(function(token) {
      current = current && current[token];
    });
    
    console.log(current);// Would be undefined if path didn't match anything in "result" var
    

    编辑

    current && ... 的目的是,如果 current 未定义(由于路径无效),脚本不会尝试评估 undefined["something"],这会引发错误。但是,我刚刚意识到如果current 恰好是假的(即false 或零或空字符串),这将无法在token 中查找该属性。所以可能支票应该是current != null

    另一个编辑

    使用Array.reduce() method

    path.split('.').reduce(
      function(memo, token) {
        return memo != null && memo[token];
      },
      resultJson
    );
    

    这也更好,因为它不需要任何vars

    【讨论】:

    • 干杯。我添加了另一个解决方案。好多了。
    猜你喜欢
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 2016-10-21
    • 2015-04-26
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多