我有一个字符串:
str_rfrnc = '["text"]["title"]["res"]["din"]'
我加载了一个json:
data = json.loads(myjson)
以下代码可以正常工作:
print(data["text"]["title"]["res"]["din"])
如何将字符串用于与上述相同的结果?
print(data[str_rfrnc]) #This fails
答案 0 :(得分:1)
这是最简单的解决方案:
>>> str_rfrnc = '["text"]["title"]["res"]["din"]'
>>> data = { 'text': { 'title': { 'res': { 'din': 10 } } } }
>>> eval('data' + str_rfrnc)
10
请注意,仅当您信任eval
的内容时,才应使用str_rfrnc
。
答案 1 :(得分:0)
这是不使用eval
的解决方案:
>>> from operator import getitem
>>> from functools import reduce
>>> from re import split
>>> str_rfrnc = '["text"]["title"]["res"]["din"]'
>>> data = { 'text': { 'title': { 'res': { 'din': 10 } } } }
>>> fields = split(r'[\[\]"]+', str_rfrnc)[1:-1]
>>> fields
['text', 'title', 'res', 'din']
>>> reduce(getitem, fields, data)
10