通过键路径从嵌套的JSON字典中获取值,而无需使用eval

Tho*_*ing 3 javascript json eval

我想通过动态构造的键路径访问嵌套的JSON字典。
密钥路径使用标准的JSON点和下标运算符。(.[x]
例如:

var data = 
{"title": "a_title",
 "testList": [
   {
     "testListItemKey": "listitem1"
   },
   {
     "testListItemKey": "listitem2",
          "deepTestList": [
            {
              "testListItemKey": "listitem1",
                      "testListItemDict":{
                         "subTitle": "sub_title",
                      }
            }]
   }]
}
Run Code Online (Sandbox Code Playgroud)

密钥路径字符串的示例为:

data.feedEntries[0].testList[2].deepTestList[1].testListItemDict.subTitle  
Run Code Online (Sandbox Code Playgroud)

到目前为止,我发现的最简单的工作解决方案是使用eval或函数构造函数:

function valueForKeypPath(data, keyPath) {
    "use strict";
    var evaluateKeypath = new Function('data', 'return data.' + keyPath);
    return evaluateKeypath(data);
}
Run Code Online (Sandbox Code Playgroud)

由于我无法完全信任从远程端点接收到的JSON数据,因此我想避免使用evalet.al。

Pet*_*tai 5

全部替换"[",以".""]"""等你拿

feedEntries.0.testList.2.deepTestList.1.testListItemDict.subTitle
Run Code Online (Sandbox Code Playgroud)

像使用path一样将其拆分为一个路径数组。split('.')

var paths =  ['feedEntries','0','testList','2']
Run Code Online (Sandbox Code Playgroud)

然后就

var root = data;
paths.forEach(function(path) {
   root = root[path];
});
Run Code Online (Sandbox Code Playgroud)

根目录末尾包含所需的数据片段。