3

I want to access a nested JSON dictionary via dynamically constructed keypath.
The keypath uses standard JSON dot and subscript operators. (. and [x])
E.g.:

var data = 
{"title": "a_title",
 "testList": [
   {
     "testListItemKey": "listitem1"
   },
   {
     "testListItemKey": "listitem2",
          "deepTestList": [
            {
              "testListItemKey": "listitem1",
                      "testListItemDict":{
                         "subTitle": "sub_title",
                      }
            }]
   }]
}

An example keypath string would be:

data.feedEntries[0].testList[2].deepTestList[1].testListItemDict.subTitle  

The simplest working solution I found so far is to use eval or function constructors:

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

As I can't fully trust the JSON data I receive from a remote endpoint, I'd like to avoid eval et.al.

Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112
  • possible duplicate of [In javascript how can I dynamically get a nested property of an object](http://stackoverflow.com/questions/6906108/in-javascript-how-can-i-dynamically-get-a-nested-property-of-an-object) – Quentin Apr 28 '13 at 08:22
  • This has been asked a number of times .. – user2246674 Apr 28 '13 at 08:27

2 Answers2

5

Replace all "[" to "." and "]" to "" so you get to

feedEntries.0.testList.2.deepTestList.1.testListItemDict.subTitle

Split this into a path array like using path.split('.')

var paths =  ['feedEntries','0','testList','2']

then just

var root = data;
paths.forEach(function(path) {
   root = root[path];
});

at the end root contains the desired data fragment.

Peter Aron Zentai
  • 11,482
  • 5
  • 41
  • 71
0

What if you are using "underscore", I recommend underscore-keypath

jeeeyul
  • 3,727
  • 1
  • 24
  • 37