使用字符串作为JSON对象中的参数来检索值

时间:2018-09-13 19:56:52

标签: python python-3.x

我有一个字符串:

str_rfrnc = '["text"]["title"]["res"]["din"]'

我加载了一个json:

data = json.loads(myjson)

以下代码可以正常工作:

print(data["text"]["title"]["res"]["din"])

如何将字符串用于与上述相同的结果?

print(data[str_rfrnc]) #This fails

2 个答案:

答案 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