Right, you can't treat a string ("['c']['d']"
) as Python code like that. There's no native syntax to support something like that, but if you store the path in a list or tuple, like:
nav = ('c', 'd')
Then we can use a loop to retrieve the desired value:
testobj = {'a': 'b', 'c': {'d': {'e':'f'}}}
for k, v in testobj.items():
print(f"k:{k}, v:{v}") #OK
nav = ('c', 'd')
mark = testobj
for k in nav:
mark = mark[k]
print(f'path {nav}: {mark}')
Which produces:
k:a, v:b
k:c, v:{'d': {'e': 'f'}}
path ('c', 'd'): {'e': 'f'}
There are also modules such as jmespath and others that allow you to use dot notation to navigate python objects:
import jmespath
testobj = {'a': 'b', 'c': {'d': {'e':'f'}}}
for k, v in testobj.items():
print(f"k:{k}, v:{v}") #OK
nav = 'c.d'
mark = jmespath.search(nav, testobj)
print(f'path {nav}: {mark}')
Which produces:
k:a, v:b
k:c, v:{'d': {'e': 'f'}}
path c.d: {'e': 'f'}
Or, using /
delimited paths in jsonpointer:
import jsonpointer
testobj = {'a': 'b', 'c': {'d': {'e':'f'}}}
for k, v in testobj.items():
print(f"k:{k}, v:{v}") #OK
nav = '/c/d'
mark = jsonpointer.resolve_pointer(testobj, nav)
print(f'path {nav}: {mark}')
Which produces:
k:a, v:b
k:c, v:{'d': {'e': 'f'}}
path /c/d: {'e': 'f'}